C# Windows服务 UDP通信

klx019 klx019 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我写了一个udp通信的程序,在UDPServer类中有接收方法,在主程序中创建对象调用方法,程序执行后能够正长和客户端通信,但是我把他封装成服务时,只能发数据,不能接收数据。我使用WireShark抓包能够抓到客户端发过来的数据包,这说明是服务端的接收数据包的函数没被调用,不明白是怎么回事,请求帮助。

UDPServer类
#region 接收UDP客户端发来的信息
public void ReceiveDataUDPServer()
{//接收从UDP通信客户端发来的信息
int MyPort = 8800;
string MyInfo="";
string MyIP="";
byte[] MyData= new byte[300];
datagram = new Datagram();
MyServer = new UdpClient(8800);
while (true)
{
Debug.WriteLine("Begin receive!");
try
{
Debug.WriteLine("Begin receive!");
IPEndPoint MyRemoteEndPoint = null;
MyData= MyServer.Receive(ref MyRemoteEndPoint);
MyInfo = System.Text.Encoding.Default.GetString(MyData);
MyIP = MyRemoteEndPoint.Address.ToString();
Debug.WriteLine(MyIP+":"+MyPort);
Debug.WriteLine("data:"+MyInfo);

}
catch (Exception ex)
{
// Debug.WriteLine("cuo");
Debug.WriteLine(ex.Message);
}

}

}


public void Receive()
{//创建UDP通信服务端接收信息

IPHostEntry hostName = Dns.GetHostEntry(Dns.GetHostName());
string MyIP = hostName.AddressList[0].ToString();
int MyPort = 8800;
IPEndPoint MyRemoteEndPoint = new IPEndPoint(IPAddress.Parse(MyIP), MyPort);
MyThread = new System.Threading.Thread(new ThreadStart(this.ReceiveDataUDPServer));
MyThread.IsBackground = true;
MyThread.Start();
}
#endregion

客户端的发送方法:
#region 发送数据到UDP客户端
public static void Send(byte[] MyData, string MyIP, int MyPort)
{//消息发送方法
Debug.WriteLine("The Client ip is :"+MyIP);
IPEndPoint MyRemoteEndPoint = new IPEndPoint(IPAddress.Parse(MyIP), MyPort);
UdpClient MyClient = new UdpClient();
MyClient.Send(MyData, MyData.Length, MyRemoteEndPoint);
Debug.WriteLine("After send datas!");
}
#endregion
}

服务启动时调用UDPServer的接收方法
protected override void OnStart(string[] args)
{
UDPServer udp = new UDPServer();
udp.Receive();
}
...全文

相关推荐

C# Socket Udp 通信服务器端(Windows Server)

C# Socket Udp 通信服务器端,一个封装好的Windows 服务,端口是10000

zhangpengshou

C#中基于Socket的电文通信与Windows服务集成实战

最常见的解决方案是在每条消息前添加一个长度字段头,形成“头+体”结构:发送时先发送4字节长度(Big-Endian),再发送正文;接收时先读4字节获知总长,再循环读取后续数据。// 确保读满4字节// 完整读取消息体if (received == 0) throw new IOException("连接关闭");代码逻辑逐行解读:首先读取4字节头部,解析出消息体长度;自动处理字节序转换(相当于判断并反转);- 调用ReceiveAll。

己见明

c# udp server and client

c# udp server and client,自己写的一个UDP程序,有服务器和客户端,且可以在WINDOWS MOBILE手机上测试通过,要在手机上用的话要自己做压缩包。0分分享。

fisher

主从服务器之间socket的通信

本程序实现了主服务向局域网内广播消息, 从服务器收到消息后自动向主服务器注册, 并且传输文件。主服务器可以对注册的从服务器进行管理进行测试时建立路径D:\_workSpace\xml 并且在此文件夹下放xml文件。本程序绝对可以运行, 但只是希望提供资料而不是直接拿来用。

向着朝阳出发

Client-Server-Using-UDP.zip_UDP_server client_udp csharp server

客户端服务器交互演示使,初学者可下载做参考。

寒泊
评论
收藏 已收藏
分享
返回顶部
klx019
C# 111,130 成员 642,541 内容