服务器:
TCP:
并发服务器
UDP:
重复服务器
客户端:
数据报套接字:
接受和发送使用API:ReceiveFrom()和SendTo()
流式套接字:
接收和发送使用API:Receive()和Send()
private static void ClientAndServer()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//参数指定本机IP地址
localHost = new IPEndPoint(IPAddress.Any, 8080);
//将本机IP地址和端口与套接字绑定,为接收做准备
socket.Bind(localHost);
//定义远程IP地址和端口(实际使用时应为远程主机IP),为发送数据作准备
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
EndPoint remoteHost = (EndPoint)remoteIPEndPoint;
Console.Write("输入发送的信息:");
string tmpStr = Console.ReadLine();
dataBytes = Encoding.UTF8.GetBytes(tmpStr);
socket.SendTo(dataBytes, dataBytes.Length, SocketFlags.None, remoteHost);
while (true)
{
Console.WriteLine("等待接收....");
dataLength = socket.ReceiveFrom(dataBytes, ref remoteHost);
tmpStr = Encoding.UTF8.GetString(dataBytes, 0, dataLength);
Console.WriteLine("接收到的信息:"+tmpStr);
if (tmpStr == "exit") break;
Console.Write("输入回送信息(exit退出):");
tmpStr = Console.ReadLine();
dataBytes = Encoding.UTF8.GetBytes(tmpStr);
socket.SendTo(dataBytes,remoteHost);
}
socket.Close();
Console.WriteLine("对方已经退出,请按Enter键结束");
Console.ReadLine();
}