上网查看很多的说法,UDP协议是不分客户端和服务端的...那我就不太清楚了!毕竟没大牛带,都考自己的理解,顺便自己做个总结吧! 基本框架都是偷了一些大神的,但小弟稍做了些修改!这能实现。服务端能自动跟踪客户端的信息来源
好了不多说!上代码:
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
//类名 服务端
namespace UdpSocket{
class Program
{
/// <summary>
/// 流程
/// 1.定义作为客户端的IP以及Prot的位置
/// 2.开启线程
/// 3.定义发送信息的方法
/// 4.定义接收信息的方法
/// </summary>
///
static Socket socket; //全局定义一个Socket的方法
static IPEndPoint revpoint = new IPEndPoint(IPAddress.Any, 0);//创建一个实例,用来接收客户端传回来的信息,该方法必须与接收的方法参数一致
static EndPoint Remete = (EndPoint)(revpoint);//把revpoint标识为网络标识地址
public static void Main(string[] args)
{
XmlRead xm = new XmlRead();
//先和Socket建立连接,设置该方法的地址(IP以及prot)
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string Ip = xm.ReadXMLIpAndProt("GPS_IP");//192.168.1.111
string Prot = xm.ReadXMLIpAndProt("GPS_Prot");//30020
socket.Bind(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Prot)));
//开启线程
Console.Write("服务器已经开启");
Thread thread = new Thread(ReciveMsg);
thread.Start();
Thread thread2 = new Thread(SendMsg);
thread2.Start();
}
//定义发送的方法,传进线程
static void SendMsg()
{
//该方法指定,跟谁建立连接
while (true)
{
string msg = Console.ReadLine();//定义输入内容
socket.SendTo(Encoding.UTF8.GetBytes(msg), Remete);//由于项目需求,客户端的自身IP以及Prot会随时变化,
//所以不能定义固定,留意Remete的参数,该位置的参数是定义传输方向,
//所以调用上面的Remete
}
}
//定义个接收的方法,传进线程
static void ReciveMsg()
{
while (true)
{
revpoint = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = new byte[1024];
int length = socket.ReceiveFrom(buffer, ref Remete);
string message = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine( message);
}
}
}
}
//客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UdpSocketClient
{
class Program
{
static Socket client;
static void Main(string[] args)
{
//该方法是建立本端口的资料
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.111"),7001));
Thread t1 = new Thread(SendMsg);
t1.Start();
Thread t2 = new Thread(ReciveMsg);
t2.Start();
}
static void SendMsg()
{
//发送方法需要填写的是,发送到那个设备的IP和Prot
EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.1.111"),30020);
while (true)
{
string msg = Console.ReadLine();
client.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
}
static void ReciveMsg()
{
while (true)
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
byte[] bytes = new byte[1024];
int length = client.ReceiveFrom(bytes, ref point);
string message = Encoding.UTF8.GetString(bytes, 0, length);
Console.WriteLine(point.ToString() + message);
}
}
}
}