【Unity】使用Socket建立客户端和服务端并进行通信的例子

Socket服务端:

using System;

using System.Collections.Generic;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

public class SocketServer

{

public static Socket listenSocket;//监听Socket

public static List clientList = new List();//客户端列表

static void Main(string[] args)

{

//创建监听Socket,并绑定ip

listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);

listenSocket.Bind(ip);

//设定监听最大数量

listenSocket.Listen(100);

Thread thread = new Thread(Listen);

thread.IsBackground = true;

thread.Start();

Console.ReadKey();

}

static void Listen()

{

Console.WriteLine("开始监听");

while(true)

{

//开始监听,若监听到访问则创建一个Socket表示与其的连接

Socket newSocket = listenSocket.Accept();

Console.WriteLine("有客户端连接");

//告诉其他客户端,有客户端登录

foreach(Socket socket in clientList)

{

socket.Send(new UTF8Encoding().GetBytes(newSocket.RemoteEndPoint.ToString() + "已经上线"));

}

//添加至列表

clientList.Add(newSocket);

//创建线程监听客户端发来的消息

Thread thread = new Thread(ReceiveMsg);

thread.IsBackground = true;

thread.Start(newSocket);

}

}

static void ReceiveMsg(Object Obj_)

{

Socket socket = (Socket)Obj_;

while (true)

{

try

{

byte[] bs = new byte[1024];

socket.Receive(bs);

Console.WriteLine(socket.RemoteEndPoint.ToString() + ":" + new UTF8Encoding().GetString(bs) + "\n");

}

catch

{

Console.WriteLine("有客户端掉线");

clientList.Remove(socket);

return;

}

}

}

}

Socket客户端:

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

public class SockClient

{

public static Socket socket;

static void Main(string[] args)

{

//创建代表本地的socket

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//创建要连接的ip并尝试连接该ip

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);

socket.Connect(ip);

Thread thread = new Thread(ReceiveServerMessage);

thread.IsBackground = true;

thread.Start();

while(true)

{

string content = Console.ReadLine();

//发送消息

socket.Send(new UTF8Encoding().GetBytes(content));

}

}

static void ReceiveServerMessage()

{

while(true)

{

//接收来自服务端的消息

byte[] bs = new byte[1024];

socket.Receive(bs);

Console.WriteLine(socket.RemoteEndPoint.ToString() + ":" + new UTF8Encoding().GetString(bs) + "\n");

}

}

}

你可能感兴趣的:(Unity,unity,游戏引擎,游戏开发,网络)