//下面是主机发送
//实例化一个UdpClient
UdpClient udp = new UdpClient();
//向IP地址为192.168.0.68的机器发送数据,端口设置为8001
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.68"), 8001);//这里的8001不清楚
//发送
udp.send("发送内容",iep);...........
//下面是客户端192.168.0.68的机器接收
...........
//实例化一个UdpClient
UdpClient udp = new UdpClient();
IPEndPoint iep = new IPEndPoint(IPAddress.Any,8001););//这里的8001不清楚
udp.Recieve(ref iep);
请问,我在发送中设置的端口8001,应该是指的192.168.0.68机器的端口吧?
在接收中IPEndPoint iep = new IPEndPoint(IPAddress.Any,8001);,这里设置的8001应该是192.168.0.68机器的端口吧,如果这里我设置为别的端口号,是不是192.168.0.68的机器就收不到主机发来的消息了?
最终就是想问一下,发送和设置的端口是不是都针对接收方的?是否必须保持一致?呵呵,谢谢:)
udp.Recieve(ref iep);
本机在哪个端口接受数据.双方通讯时端口要一致.
{
Send("hello how are you");
Send("byebye");
Console.ReadLine();
}
private static void Send(string message)
{
UdpClient client = new UdpClient(8081);
try
{
Console.WriteLine("send messge to server");
byte[] send = Encoding.Unicode.GetBytes(message);
client.Send(send, send.Length, "127.0.0.1", 8080);
if (message == "byebye")
{
Console.WriteLine("ok exit");
return;
}
IPEndPoint host = null;
byte[] receive = client.Receive(ref host);
Console.WriteLine("receive message:{0}", Encoding.Unicode.GetString(receive));
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
{
StartListener();
Console.ReadLine();
} private static void StartListener()
{
UdpClient server = new UdpClient(8080);
IPEndPoint myhost = null;
try
{
while (true)
{
Console.WriteLine("wait for receive");
byte[] receive = server.Receive(ref myhost);
string str = Encoding.Unicode.GetString(receive, 0, receive.Length);
Console.WriteLine("receive information:{0}", str);
if (str == "byebye")
break;
Console.WriteLine("send message" + "hello glad to see you");
byte[] send = Encoding.Unicode.GetBytes("hello glad to see you");
server.Send(send, send.Length, "127.0.0.1", 8081);
}
server.Close();
Console.WriteLine("Bye Bye please enter entry fo exit");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}