greyhh

记录学习中的点点滴滴

导航

Socket通信

Posted on 2018-03-28 16:52  greyhh  阅读(175)  评论(0编辑  收藏  举报

序言

Socket通信通用测试工具

 

代码

服务器类SocketServer.cs

 

namespace SocketCom
{
    public class SocketServer
    {
        public string IP = "127.0.0.1";
        public int Port = 8088;
        public int MaxConnectCount = 10;
        public int ReceiveBufferSize = 1024;
        public Action<Socket, int, byte[]> MessageHandler;
        public int ConnectedCount { get { return clientSockets.Count; } }

        private byte[] receiveBuffer;
        private Socket serverSocket;
        private List<Socket> clientSockets;

        public SocketServer()
        {
            receiveBuffer = new byte[ReceiveBufferSize];
            clientSockets = new List<Socket>();
        }
        public SocketServer(string ip, int port, int maxCount = 10, int recSize = 1024)
        {
            this.IP = ip;
            this.Port = port;
            this.MaxConnectCount = maxCount;
            this.ReceiveBufferSize = recSize;
            receiveBuffer = new byte[ReceiveBufferSize];
            clientSockets = new List<Socket>();
        }
        public void Start()
        {
            IPAddress ip = IPAddress.Parse(IP);
            IPEndPoint ip_end_point = new IPEndPoint(ip, Port);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(ip_end_point);
            serverSocket.Listen(MaxConnectCount);
            Thread thread = new Thread(ConnectServer);
            thread.Start();
            Console.WriteLine("服务器已启动!");
        }

        public void SendMessage(Socket socket, int mesType, byte[] data)
        {
            socket.Send(Common.WriteMessage(data,mesType));
        }
        public void SendMessageToAll(int mesType,byte[] data)
        {
            for (int i = 0; i < clientSockets.Count; i++)
            {
                if(clientSockets[i].Connected)
                clientSockets[i].Send(Common.WriteMessage(data, mesType));
            }
        }

        private void RecieveMessage(object clientSocket)
        {
            Socket mClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    int receiveNumber = mClientSocket.Receive(receiveBuffer);
                    ByteBuffer buff = new ByteBuffer(receiveBuffer);
                    int mesType = buff.ReadInt();
                    int len = buff.ReadInt();
                    byte[] data = buff.ReadBytes(len);
                    //Console.WriteLine("客户端发来消息:数据类型:{0} 数据长度:{1} 数据内容:{2}", mesType.ToString(), len, data);
                    if (MessageHandler != null)
                        MessageHandler(mClientSocket,mesType,data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    mClientSocket.Shutdown(SocketShutdown.Both);
                    mClientSocket.Close();
                    break;
                }
            }
        }
        private void ConnectServer()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                Console.WriteLine("客户端{0}成功连接", clientSocket.RemoteEndPoint.ToString());
                clientSockets.Add(clientSocket);
                string mes = "Connected To Server Successfully";
                clientSocket.Send(Common.WriteMessage(mes.ToBytes(),200));
                Thread thread = new Thread(RecieveMessage);
                thread.Start(clientSocket);
            }
        }  
    }
}

 

客户端类SocketClient.cs

namespace SocketCom
{
    public class SocketClient
    {
        public string IP = "127.0.0.1";
        public int Port = 8088;
        public int ReceiveBufferSize = 1024;
        public bool IsConnected = false;
        public Action<Socket, int, byte[]> MessageHandler;

        private byte[] receiveBuffer;
        private Socket clientSocket;

        public SocketClient()
        {
            receiveBuffer = new byte[ReceiveBufferSize];
        }
        public SocketClient(string ip, int port, int recSize = 1024)
        {
            this.IP = ip;
            this.Port = port;
            this.ReceiveBufferSize = recSize;
            receiveBuffer = new byte[ReceiveBufferSize];
        }
        public void Connect()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress mIp = IPAddress.Parse(IP);
            IPEndPoint ip_end_point = new IPEndPoint(mIp, Port);
            try
            {
                clientSocket.Connect(ip_end_point);
                IsConnected = true;
                Thread thread = new Thread(RecieveMessage);
                thread.Start(clientSocket);
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                IsConnected = false;
                Console.WriteLine("连接服务器失败");
                return;
            }
        }

        public void SendMessage(int mesType,string data="")
        {
            SendMessage(mesType,data.ToBytes());
        }
        public void SendMessage(int mesType,byte[] data)
        {
            if (IsConnected == false)
                return;
            try
            {
                clientSocket.Send(Common.WriteMessage(data, mesType));
            }
            catch
            {
                IsConnected = false;
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }
        public void Close()
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
        private void RecieveMessage(object serverSocket)
        {
            Socket myServerSocket = (Socket)serverSocket;
            while (true)
            {
                try
                {
                    int receiveNumber = myServerSocket.Receive(receiveBuffer);
                    ByteBuffer buff = new ByteBuffer(receiveBuffer);
                    int mesType = buff.ReadInt();
                    int len = buff.ReadInt();
                    byte[] data = buff.ReadBytes(len);
                    //Console.WriteLine("服务器发来消息:数据类型:{0} 数据长度:{1} 数据内容:{2}", mesType.ToString(), len, data);
                    if (MessageHandler != null)
                        MessageHandler(myServerSocket, mesType,data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myServerSocket.Shutdown(SocketShutdown.Both);
                    myServerSocket.Close();
                    break;
                }
            }
        }
    }
}

 

测试

只需简单配置一下,然后就可以专注于具体业务逻辑。

服务器

       static void Main(string[] args)
        {
            SocketServer server = new SocketServer();
            server.IP = "127.0.0.1";
            server.Port = 9001;
            server.ReceiveBufferSize = 102400;
            server.MessageHandler += MessageHandle;
            server.Start();
            Console.ReadKey();
        }

客户端

       static void Main(string[] args)
        {
            SocketClient mSocketClient;
            mSocketClient = new SocketClient();
            mSocketClient.IP = "127.0.0.1";
            mSocketClient.Port = 9001;
            mSocketClient.ReceiveBufferSize = 102400;
            mSocketClient.MessageHandler += MessageHandle;
            mSocketClient.Connect();
        }

测试处理函数

private static void MessageHandle(Socket mySocket,int type, byte[] data)
        {
            if (type == (int)MessageType.Request)
                mySocket.SendMessage((int)MessageType.Data,"服务器接收到Request请求");
            if (type == (int)MessageType.Picture)
                mySocket.SendMessage((int)MessageType.Data, "服务器接收到图片请求");    
            if (type == (int)MessageType.Data)
                mySocket.SendMessage((int)MessageType.Data,"服务器接收到数据请求");
            if (type == (int)MessageType.Other)
                mySocket.SendMessage((int)MessageType.Data,"服务器接收到其他请求");
        }

 

总结

服务器暂时没有处理客户端断开连接,后面会加一个心跳包来检测。

下载地址:https://github.com/jerryleeCP/SocketCom