Server:
class Server
{
static int port = 17333;
static void Main(string [] args) {
//CreatTCPServer();
CreatUDPClient();
Console.ReadKey();
}
static void CreatTCPServer() {
TcpListener listener = new TcpListener(System.Net.IPAddress.Any , port);
listener.Start();
Console.WriteLine("等待连接...");
while (true) {
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte [] bs = Encoding.ASCII.GetBytes("www.baidu.com");
ns.Write(bs , 0 , bs.Length);
ns.Close();
}
}
static void CreatUDPClient() {
UdpClient listener = new UdpClient(port);
IPEndPoint remote = new IPEndPoint(IPAddress.Any , port);
try {
while (true) {
byte [] data = listener.Receive(ref remote);
Console.WriteLine("remote:" + remote);
Console.WriteLine("msg:" + Encoding.ASCII.GetString(data , 0 , data.Length));
}
}
catch (SocketException e) {
Console.WriteLine(e.ToString());
}
finally {
listener.Close();
}
}
}
Client:
class Client
{
static int port = 17333;
static void Main(string [] args) {
//CreatTCPClient();
CreatUDPClient();
Console.ReadKey();
}
static void CreatUDPClient() {
UdpClient client = new UdpClient();
IPEndPoint remote = new IPEndPoint(IPAddress.Parse("88.22.23.203") , port);
byte [] b = Encoding.ASCII.GetBytes("www.baidu.com");
client.Send(b , b.Length , remote);
Console.WriteLine("send msg to server.");
}
static void CreatTCPClient() {
TcpClient client = new TcpClient("88.22.23.203" , port);
NetworkStream ns = client.GetStream();
byte [] b = new byte [1024];
int len = ns.Read(b , 0 , b.Length);
string str = Encoding.ASCII.GetString(b , 0 , len);
Console.WriteLine("Str:" + str);
}
}
推荐使用下面的UDP框架(服务器+客户端),集成了KCP,确保数据不丢包,扩展也方便,里面有一套心跳机制以及重连机制。
Unity+UDP