【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<Socket> clientList = new List<Socket>();//客户端列表

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");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值