C# TCPlistener服务器客户端和客户端服务器(从服务器向客户端发送消息)
我要做的就是从服务器向客户端发送消息。我尝试了很多教程等,但仍然无法将消息从服务器发送到客户端。 从客户机到服务器的发送很简单,并且有代码。当客户端向服务器发送“HI”时,我想向客户端响应HI。但不知道我应该在代码中添加什么。有人能帮我吗?请不要重复我知道有很多类似的话题,但找不到解决方案 服务器代码:C# TCPlistener服务器客户端和客户端服务器(从服务器向客户端发送消息),c#,sockets,tcplistener,C#,Sockets,Tcplistener,我要做的就是从服务器向客户端发送消息。我尝试了很多教程等,但仍然无法将消息从服务器发送到客户端。 从客户机到服务器的发送很简单,并且有代码。当客户端向服务器发送“HI”时,我想向客户端响应HI。但不知道我应该在代码中添加什么。有人能帮我吗?请不要重复我知道有很多类似的话题,但找不到解决方案 服务器代码: private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { IPAddress ip = Dns.Ge
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
};
while (true)
{
client = server.AcceptTcpClient();
byte[] receivetBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivetBuffer, 0, receivetBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach(byte b in receivetBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
////Resive message :
if (msg.ToString() =="HI")
{
///@EDIT 1
///// HERE Is SENDING MESSAGE TO CLIENT//////////
int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
stream.Write(sendData, 0, sendData.Length);
}
}
客户端代码:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string serverIP = "localhost";
int port = Convert.ToInt32(8555);
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("HI" + ";");
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
///////////////////////////////HERE I WANT A read message from server/
/////////////////////////////////////////////////////////////////////
stream.Close();
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
}
试试这是我的客户端和服务器版本,如果有任何参考问题,请随意询问,客户端等待服务器(联机),然后服务器是否联机连接它 方法连接到服务器
private void Connectwithserver(ref TcpClient client)
{
try
{
//this is server ip and server listen port
server = new TcpClient("192.168.100.7", 8080);
}
catch (SocketException ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
RunBoTClient();
}
}
byte[] data = new byte[1024];
string stringData;
TcpClient client;
private void RunClient()
{
NetworkStream ns;
Connectwithserver(ref client);
while (true)
{
ns = client.GetStream();
//old
// ns.ReadTimeout = 50000;
//old
ns.ReadTimeout = 50000;
ns.WriteTimeout = 50000;
int recv = default(int);
try
{
recv = ns.Read(data, 0, data.Length);
}
catch (Exception ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
//try to reconnect if server not respond
RunClient();
}
//READ SERVER RESPONSE/MESSAGE
stringData = Encoding.ASCII.GetString(data, 0, recv);
}
}
服务器
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//IF YOU WANT TO WRITE BACK TO CLIENT USE
string yourmessage = console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
//---write back the text to the client---
Console.WriteLine("Sending back : " + yourmessage );
nwStream.Write(sendBytes, 0, sendBytes.Length);
client.Close();
}
listener.Stop();
当它的服务器+客户机时,您是否尝试过像在客户机中那样写入流?我编辑了服务器代码并添加了向客户机发送消息。但是我怎样才能重新发送呢?TCP不是消息传递。这是一个每个方向的字节流,您通过调用
Write
放入该流中的字节数不能保证与某个调用Read
得到相同字节数的字节数相匹配。您需要注意Read
返回的内容,如果您想要消息传递,您必须在TCP上实现它(或切换到执行此操作的协议)。我为服务器编辑了代码,并添加了向客户端发送消息。但是我怎样才能重新给它播种子呢?我是看着你的代码做的。@adam如果你在使用路由器,在pc1上运行客户端代码,在与同一路由器连接的pc2上运行服务器代码,然后使用该电脑的专用ip运行服务器程序,然后将该服务器的专用ip和端口提供给客户端,然后运行客户端,两者都将根据我自己的代码进行通信,您的示例。我现在需要从服务器读取消息。@adam我已经编辑了代码,现在服务器将要求您输入字符串,然后发送回客户端。我知道如何写回代码,请。。。我现在想读关于客户的书。