gpt4 book ai didi

c# - 套接字通信程序测试

转载 作者:行者123 更新时间:2023-11-28 20:47:46 24 4
gpt4 key购买 nike

我从使用简单的 UDPClient 程序发送一些数据的套接字编程开始。大代码片段如下:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class ShowIP
{
public static void Main(string[] args)
{
string name = Dns.GetHostName();
//name = "GSL1460";
name = "GSL1296";
try
{
IPAddress[] addrs = Dns.GetHostEntry(name).AddressList;
foreach (IPAddress addr in addrs)
Console.WriteLine("{0}/{1}", name, addr);

Console.WriteLine("Started listening");
Thread listenerThread = new Thread(new ThreadStart(StartListeningUDP));
listenerThread.Start();

Console.WriteLine("Started sending");
for (int counter = 0; counter <= 3; counter++)
{
Thread.Sleep(1000);
Console.WriteLine("Sending {0} time", counter.ToString());
StartSendingUDP(addrs[0]);
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

private static void StartListeningUDP()
{
UdpClient udpListener = null;
IPEndPoint nwPoint = new IPEndPoint(IPAddress.Any, 12345);

while (true)
{
try
{
udpListener = new UdpClient(12345);
Console.WriteLine("Waiting to receive");
Byte[] receivedBytes = udpListener.Receive(ref nwPoint);
string receivedData = Encoding.ASCII.GetString(receivedBytes);

Console.WriteLine("Data received : " + receivedData);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
udpListener.Close();
}
}
}

private static void StartSendingUDP(IPAddress clientAddress)
{
UdpClient udpSender = new UdpClient();
try
{
Byte[] sendBytes = Encoding.ASCII.GetBytes("Say HI to Papa...");

Console.WriteLine("Data Sent : Say HI to Papa...");
udpSender.Send(sendBytes, sendBytes.Length, new IPEndPoint(clientAddress, 12345));
}
finally
{
udpSender.Close();
}

}
}

该示例在本地机器上运行良好,但无法将数据发送到 Intranet 上的另一台机器。

测试期间

  • 正在取消注释将数据发送到他的机器的适当代码
  • 正在他的机器上运行 Receiver bit
  • 已检查他的机器上是否打开了所需的端口

我错过了什么吗?请提出建议。

最佳答案

udpSender.Flush?

关于c# - 套接字通信程序测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com