C#中使用UDP通信
2014-07-10 15:20
141 查看
UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。
服务器端代码:
C#代码
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//关闭连接
}
}
客户端代码:
C#代码
static void Main(string[] args)
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
}
}
服务器端代码:
C#代码
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//关闭连接
}
}
客户端代码:
C#代码
static void Main(string[] args)
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
}
}
相关文章推荐
- C#中使用UDP通信实例
- 使用C#实现基于TCP和UDP协议的网络通信程序的基本示例
- C#使用 UdpClient 类进行简单通信的例子
- C#中使用UDP通信
- C#使用UdpClient类进行简单通信的实例
- C#串口通信:MSComm控件使用详解
- C#的SerialPort使用,动态创建串口连接,短信猫通信
- 使用C#来开发.NET CF 蓝牙通信模块(转载)
- C#简单的UDP通信例子
- C#使用UDP Client编写聊天程序
- C# SOCKET UDP通信实例
- 使用C#来开发.NET CF 蓝牙通信模块(转载)
- 在C#中使用SerialPort类实现串口通信 遇到多线程问题
- C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP),多多宜善
- C#完整的通信代码(一)(点对点,点对多,同步,异步,UDP,TCP)
- C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP)
- C# 使用ICallbackEventHandler实现客户端服务器端异步通信
- ExternalInterface在Flex Project中C#,C++通信使用上的不同
- C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP)
- C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP),多多宜善。