1、UDP 客户端
//由于收发都在本机,所以只用一个IP地址
IPAddress addr= IPAddress.Parse("127.0.0.1");
var ptLocal = new IPEndPoint(addr,9001);//本机节点,用于发送var ptDst = new IPEndPoint(addr,9002);//目标节点
//在本地建立udp服务
var udp = new Udpclient(ptLocal);
bytell buffer = Encoding.UTF8.GetBytes("hello")//将内容发给ptDstudp.Send(buffer,buffer.Length,ptDst);
2、UDP服务端
//由于收发都在本机,所以只用一个IP地址
IPAddress addr= IPAddress.Parse("127.0.0.1");
var ptLocal = new IPEndPoint(addr,9001);//本机节点,用于发送var udp = new Udpclient(ptLocal);var thread = new Thread(Res)
thread.start();var ptDst = new IPEndPoint(addr,9002);//目标节点void Res()
{while(true)
{
var received =udp.Receive(ref ptDst);
string info = Encoding.UTF8.GetString(received);
info =$"{ptDst.Address}:{ptDst.Port}:{info}";
Console.WriteLine(info);
bytell buf = Encoding.UTF8.GetBytes("What are our children's names");
udp.send(buf,buf.Length,ptDst);//将内容发给ptDst
}
}
3、TCP客户端
TcpClient tcp = new Tcpclient("127.0.0.1",9002);
NetworkStreamn=tcp.GetStream();
var w = new BinaryWriter(n);
byte[] buffer = Encoding.UTF8.GetBytes("hello");
w.Write(buffer,0,buffer.Length);
Thread.Sleep(2000); //这里间隔一下 ,要不然服务器端看不到客户端 , 多个点发采用Task处理
w.Flush();
4、TCP接收端
TcpListener serv = new TcpListener(IPAddress.Any,9002);
serv.start();var thread = new Thread(Res)
thread.start();void Res{Byte[] bytes = new Byte[256];
int i;
while(true)
{
var c=serv.AcceptTcpClient();
var n=c.GetStream();
while((i=n.Read(bytes,0,bytes.Length))!=0)
{
var msg=Encoding.AsCII.GetString(bytes,0,i);
Console.WriteLine($"Received:{msg}");
mSg += ",too";
var data = Encoding.AsCII.GetBytes(msg)
n.Write(data,0,data.Length);
}
}
}