Unity网络开发记录(三):封装服务端的相关socket

客户端与服务端通讯socket

封装此类,是为了方便维护客户端和服务端建立连接后返回的socket

包含了所需要的基础的socket 以及 该socket所对应的id号,方便进行管理

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TechTcpServerTest2
{
    internal class ClientTcpSockt
    {
        private static int CLIENT_NUMBER = 0;
        public int clientID = 0;
        private Socket? socket;

        public ClientTcpSockt(Socket _socket)
        {
            socket = _socket;
            clientID = CLIENT_NUMBER;
            ++CLIENT_NUMBER;
        }

        public void Send(string info)
        {
            if (socket != null)
            {
                try
                {
                    socket.Send(Encoding.UTF8.GetBytes(info));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);   
                }
            }
        }

        public void Receive()
        {
            if (socket != null)
            {
                try
                {
                    if (socket.Available > 0)
                    {
                        byte[] buffer = new byte[1024 * 5];
                        int num = socket.Receive(buffer);
                        ThreadPool.QueueUserWorkItem(HandleMsg, Encoding.UTF8.GetString(buffer, 0, num));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        private void HandleMsg(object obj)
        {
            string info = (string)obj;
            if (socket != null)
            {
                Console.WriteLine("{0}客户端,信息:{1}", socket.RemoteEndPoint, info);
            }
        }

        public void Close()
        {
            if (socket != null)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                socket = null;
            }
        }
    }
}

服务端socket

此类具有基础的socket 以及 一个客户端类的字典,按照 特定的id与socket进行对应

对于客户端的连接请求以及消息的接收处理依旧采用多线程去处理

对于accept一直循环去监听,如果有新连接就加入到字典当中

对于receive,就一直循环的调用字典中存储对象的receive方法

关闭对客户端的连接,只需要循环调用字典内 刚刚封装的客户端-服务端socket对象中的关闭方法就行

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TechTcpServerTest2
{
    internal class ServerTcpSocket
    {
        private Socket socket;
        private Dictionary<int, ClientTcpSockt> clientDic = new Dictionary<int, ClientTcpSockt>();
        private bool isConnected;
        public bool IsConnected => isConnected;

        public void Start(string ip, int port, int num)
        {
            isConnected = false;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            socket.Bind(ipPoint);
            socket.Listen(num);

            ThreadPool.QueueUserWorkItem(Accept);
            ThreadPool.QueueUserWorkItem(Receive);
        }

        public void Accept(object obj)
        {
            while (!isConnected)
            {
                try
                {
                    Socket client = socket.Accept();
                    ClientTcpSockt clientTcpSockt = new ClientTcpSockt(client);
                    clientDic.Add(clientTcpSockt.clientID, clientTcpSockt);
                    clientTcpSockt.Send("服务器连接成功");
                }
                catch (Exception e)
                {
                    Console.WriteLine("客户端连接出错 " + e.Message);
                }
            }
        }

        public void Receive(object obj)
        {
            while (!isConnected)
            {
                try
                {
                    if (clientDic.Count > 0)
                    {
                        foreach (var item in clientDic.Values)
                        {
                            item.Receive();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("客户端接收出错 " + e.Message);
                }
            }
        }

        public void Close()
        {
            foreach(var item in clientDic.Values)
            {
                item.Close();
            }
            clientDic.Clear();

            isConnected = true;
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            socket = null;
        }

        public void Broadcast(string info)
        {
            if (socket != null)
            {
                foreach (var item in clientDic.Values)
                {
                    item.Send(info);
                }
            }
        }
    }
}

启动

开始先初始化一个与服务相关的socket类对象,调用前面所写的start方法初始化绑定ip地址、端口号、监听大小

然后该类对象会自动进行处理相应的客户端连接,以及相关的通讯工作。对于客户端,最基本的代码connect就可以连接该服务器并进行通讯

cs 复制代码
namespace TechTcpServerTest2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ServerTcpSocket socket = new ServerTcpSocket();
            socket.Start("127.0.0.1", 8080, 1024);
            Console.WriteLine("服务器开启");
            while(true)
            {
                string input = Console.ReadLine();
                if (input == "Quit")
                {
                    socket.Close();
                }
                else if (input.Substring(0, 2) == "B:")
                {
                    socket.Broadcast(input.Substring(2));
                }
            }
        }
    }
}

启动客户端和该新的服务端后,可以发现依然能够正常连接

相关推荐
发光小北9 分钟前
Modbus TCP 转 Profinet 主站网关如何应用?
网络·网络协议·tcp/ip
易连EDI—EasyLink3 小时前
易连EDI–EasyLink实现OCR智能数据采集
网络·人工智能·安全·汽车·ocr·edi
@insist1234 小时前
信息安全工程师考点精讲:身份认证核心原理与分类体系(上篇)
大数据·网络·分类·信息安全工程师·软件水平考试
SmartRadio4 小时前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
_.Switch4 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
金色光环5 小时前
FreeModbus释放底层的 TCP 监听端口
服务器·网络·tcp/ip
数智化精益手记局5 小时前
拆解物料管理erp系统的核心功能,看物料管理erp系统如何解决库存积压与缺料难题
大数据·网络·人工智能·安全·信息可视化·精益工程
灰子学技术7 小时前
Envoy HTTP 过滤器处理技术文档
网络·网络协议·http
Olivia051405149 小时前
Voohu:音频变压器的屏蔽接地技术对50Hz工频噪声抑制的影响
网络·机器人·信息与通信
byoass9 小时前
智巢AI知识库深度解析:企业文档管理从大海捞针到精准狙击的进化之路
开发语言·网络·人工智能·安全·c#·云计算