0
我想在c#中使客户端服务器appilcation。在客户端,我向服务器发送hello消息,服务器收到消息。 一旦服务器收到消息,它应该向客户端发回消息,指示已收到消息。基本上是一种承认。 我的问题是客户端没有收到服务器的消息。 停机是我的客户端和服务器的代码。c#客户端服务器使用UDP连接
客户端部分:
string x = "192.168.1.4";
IPAddress add = IPAddress.Parse(x);
IPEndPoint point = new IPEndPoint(add, 2789);
using (UdpClient client = new UdpClient())
{
byte[] data = Encoding.UTF8.GetBytes("Hello from client");
client.Send(data, data.Length, point);
string serverResponse = Encoding.UTF8.GetString(client.Receive(ref point));
Console.WriteLine("Messahe received from server:"+ serverResponse);
}
服务器部分:
try
{
while (true)
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
Console.WriteLine("Client address is:" + groupEP.Address.ToString());
Console.WriteLine("Client port is:" + groupEP.Port.ToString());
byte[]data = new byte[1024];
UdpClient listener = new UdpClient(2789);
Console.WriteLine("Waiting for client");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received Data:"+ Encoding.ASCII.GetString(bytes, 0, bytes.Length));
//sending acknoledgment
string welcome = "Hello how are you from server?";
byte[]d1 = Encoding.ASCII.GetBytes(welcome);
listener.Send(d1, d1.Length, groupEP);
Console.WriteLine("Message sent to client back as acknowledgment");
}
}
THX的答复。我尝试了你提到的步骤,但仍然是同样的问题。 –