Example #1
0
        public void initServer(string ip, int port)
        {
            var server = new WebSocketServer(string.Format("ws://{0}:{1}", ip, port));

            server.RestartAfterListenError = true;
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    if (!clientMap.ContainsKey(socket.ConnectionInfo.ClientPort))
                    {
                        clientMap.Add(socket.ConnectionInfo.ClientPort, socket);
                    }
                };
                socket.OnClose = () =>
                {
                    if (clientMap.ContainsKey(socket.ConnectionInfo.ClientPort))
                    {
                        clientMap.Remove(socket.ConnectionInfo.ClientPort);
                    }
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine("OnMessage", socket.ConnectionInfo);
                    List <CommunicateVO> cos = CommunicateUtils.strToCommunicateVos(message);
                    Receive(socket, cos);
                };
            });
        }
        /// <summary>
        /// 接收 Client Socket 数据
        /// 私有函数不对外直接提供。
        /// 使用Receive(Socket socket, List<CommunicateVO> cos)接口监听数据
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            String      content = String.Empty;
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
                content = state.sb.ToString();

                // 是否有结束标签
                if (content.IndexOf("####") > -1)
                {
                    List <CommunicateVO> cos = CommunicateUtils.strToCommunicateVos(content);
                    Receive(handler, cos);

                    // 重置数据传输对象
                    state.cleanData();
                }
            }

            // 继续获取数据
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
                    string content = state.sb.ToString();
                    if (content.IndexOf("####") > -1)
                    {
                        List <CommunicateVO> cos = CommunicateUtils.strToCommunicateVos(content);
                        Receive(client, cos);
                    }
                    else
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                    }
                }
                else
                {
                    //string content = state.sb.ToString();
                    //if (content.IndexOf("####") >= 0)
                    //{
                    //    List<CommunicateVO> cos = CommunicateUtils.strToCommunicateVos(content);
                    //    Receive(client, cos);
                    //}

                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }