Example #1
0
        //arg 回调获取到的客户端信息
        //还未考虑多个客户端。
        public void serverStart(updateConStatus conStatus)
        {
            //创建服务器对象,默认监听本机0.0.0.0,端口5004
            server = new SocketServer(port);
            //处理从客户端收到的消息
            server.HandleRecMsg = new Action <byte[], SocketConnection, SocketServer>((bytes, client, theServer) =>
            {
                if (bufLength + bytes.Length > 110)//收到的数据超过buf,将数据清空
                {
                    bufLength = 0;
                    Array.Clear(msgBuf, 0, msgBuf.Length);
                    Console.WriteLine("recv 22 error data!!!");
                    return;
                }
                Array.Copy(bytes, 0, msgBuf, bufLength, bytes.Length);
                bufLength += bytes.Length;
                if (bufLength < 11)
                {
                    return;
                }
                checkMsg();
                //printMsg(bytes);
            });
            server.HandleSendMsg = new Action <byte[], SocketConnection, SocketServer>((msg, client, theServer) =>
            {
                // TODO
            });


            //处理服务器启动后事件
            server.HandleServerStarted = new Action <SocketServer>(theServer =>
            {
                Console.WriteLine("服务已启动************");
                //this.Invoke(new RefreshUI(refreshUI), new object[] { "服务已启动************" });
            });

            //处理新的客户端连接后的事件
            server.HandleNewClientConnected = new Action <SocketServer, SocketConnection>((theServer, theCon) =>
            {
                string clientIP = ((IPEndPoint)theCon._socket.RemoteEndPoint).Address.ToString();
                theCon.Property = clientIP;
                theServer.AddConnection(theCon);
                theDevice = theCon;
                conCount++;
                conStatus(conCount, theCon);
                Console.WriteLine($@"一个新的客户端[{clientIP}]接入,当前连接数:{theServer.GetConnectionCount()}");
            });

            //处理客户端连接关闭后的事件
            server.HandleClientClose = new Action <SocketConnection, SocketServer>((theCon, theServer) =>
            {
                theServer.RemoveConnection(theCon);
                conCount--;
                Console.WriteLine($@"一个客户端关闭,当前连接数为:{theServer.GetConnectionCount()}");
                // this.Invoke(new RefreshUI(refreshUI), new object[] { $@"一个新的客户端接入,当前连接数:{theServer.GetConnectionCount()}" });
            });

            //处理异常
            server.HandleException = new Action <Exception>(ex =>
            {
                // this.Invoke(new RefreshUI(refreshUI), new object[] { $@"ohoops,an error !!!!" });
            });

            //服务器启动
            server.StartServer();
        }
Example #2
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="socket">维护的Socket对象</param>
 /// <param name="server">维护此连接的服务对象</param>
 public SocketConnection(Socket socket, SocketServer server)
 {
     _socket = socket;
     _server = server;
 }