C#编程 socket编程之udp服务器端和客户端
2024-09-05 12:11:28
基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)
使用Udp协议通讯需要具备以下几个条件:
(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号--服务器端
(3).通过SendTo()方法向指定主机发送消息 (需提供主机IP地址及端口)
(4).通过ReciveFrom()方法接收指定主机发送的消息 (需提供主机IP地址及端口)
下面用代码实现简单的服务器---客户端通信
服务器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _023_socket编程_UDP协议_服务器端 {
class Program
{
private static Socket udpServer;
static void Main(string[] args) {
//1,创建socket
udpServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
//2,绑定ip跟端口号
udpServer.Bind( new IPEndPoint( IPAddress.Parse("192.168.1.101"),7788 ) );
//3,接收数据
new Thread(ReceiveMessage){ IsBackground = true}.Start();
Console.WriteLine("服务器启动...");
Console.ReadKey();
}
static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
}
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace _002_socket编程_udp协议_客户端 {
class Program {
static void Main(string[] args) {
//创建socket
Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
while (true)
{
//发送数据
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 7788);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
}
udpClient.Close();
Console.ReadKey();
}
}
}
执行过程:
(1)启动服务器
(2)启动客户端,并向服务器发送数据
最新文章
- ASP.NET Core 折腾笔记一
- 用jquery实现瀑布流案例
- 优化MySQL数据库性能的八大方法
- Roslyn词法分析器初使用
- JS的基础知识
- iOS7程序内部如何打开评分页面
- PHP判断用户所在国家并跳转对应的目录
- Winform设置相关
- js判断加载大小页面
- [Everyday Mathematics]20150104
- hdoj 3785 寻找大富翁【优先队列+sort排序】
- 【转】Spring注解@Component、@Repository、@Service、@Controller区别
- 关于各种数据库 Insert时同时取到Id的操作
- WebService 调用三种方法
- Unsupervised Learning and Text Mining of Emotion Terms Using R
- Gym 100963B
- 用Quartz 2D画小黄人
- BZOJ 1874 取石子游戏 - SG函数
- SW-DP (Serial Wire Debug Port) Analyzer plugin for the Saleae Logic
- C#多线程JOIN方法初探