Example #1
0
        /// <summary>
        /// 接完到完整消息后处理消息
        /// </summary>
        /// <param name="state"></param>
        private void Handle(StateObject state)
        {
            UnPackageObject unPackageObject = MQPackageHelper.UnPackage(state.totalBuffer);

            OperateObject obj = new OperateObject();

            obj.ope        = unPackageObject.ope;
            obj.body       = unPackageObject.body;
            obj.workSocket = state.workSocket;

            //加入队列
            taskQueue.Enqueue(obj);

            BaseMsgObject baseMsgObject = new BaseMsgObject();

            baseMsgObject.msgId   = unPackageObject.msgId;
            baseMsgObject.code    = 10000;
            baseMsgObject.message = $"已成功收到[{state.workSocket.RemoteEndPoint.ToString()}][{obj.ope.ToString()}]消息";

            Send(state.workSocket, baseMsgObject, MsgOperation.回复消息);
        }
Example #2
0
        public void Send(object data, MsgOperation msgOperation)
        {
            try
            {
                if (_msgId >= uint.MaxValue)
                {
                    _msgId = uint.MinValue;
                }
                _msgId++;
            }
            catch (Exception ex)
            {
                _msgId = uint.MinValue;
            }
            uint msgId = _msgId;

            byte[] sendData = MQPackageHelper.GetPackage(data, msgId, msgOperation);

            client.BeginSend(sendData, 0, sendData.Length, 0, new AsyncCallback(SendCallback), client);

            sendDone.WaitOne();
        }
Example #3
0
        private void Send(Socket handler, object data, MsgOperation msgOperation)
        {
            try
            {
                if (_msgId >= uint.MaxValue)
                {
                    _msgId = uint.MinValue;
                }
                _msgId++;
            }
            catch (Exception ex)
            {
                _msgId = uint.MinValue;
            }

            uint msgId = _msgId;

            byte[] sendData = MQPackageHelper.GetPackage(data, msgId, msgOperation);
            // Begin sending the data to the remote device.
            Console.WriteLine($"向[{handler.RemoteEndPoint.ToString()}]发送了一条消息:[{JsonConvert.SerializeObject(data)}]");
            handler.BeginSend(sendData, 0, sendData.Length, 0, new AsyncCallback(SendCallback), handler);
        }
Example #4
0
        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);
                Console.WriteLine($"[{client.LocalEndPoint.ToString()}]接收到[{bytesRead}]字节数据");
                if (bytesRead > 0)
                {
                    //不管是不是第一次接收,只要接收字节总长度小于4
                    if (state.readBufferLength + bytesRead < 4)
                    {
                        Array.Copy(state.buffer, 0, state.totalBuffer, state.readBufferLength, bytesRead);
                        state.readBufferLength += bytesRead;
                        //继续接收
                        state.buffer = new byte[StateObject.BufferSize];
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                        return;
                    }

                    //已读长度如果小于4 要先获取总的消息长度
                    if (state.readBufferLength < 4)
                    {
                        //先拼出消息体长度
                        byte[] totalLengthBytes = new byte[4];
                        if (state.readBufferLength > 0)
                        {
                            Array.Copy(state.totalBuffer, 0, totalLengthBytes, 0, state.readBufferLength);
                        }
                        int readLength = 4 - state.readBufferLength;
                        Array.Copy(state.buffer, 0, totalLengthBytes, state.readBufferLength, readLength);
                        state.totalLength = ByteConvert.Bytes2UInt(totalLengthBytes);
                        state.totalBuffer = new byte[state.totalLength];
                    }

                    //还是没读完
                    if (state.totalLength > state.readBufferLength + bytesRead)
                    {
                        Array.Copy(state.buffer, 0, state.totalBuffer, state.readBufferLength, bytesRead);
                        state.readBufferLength += bytesRead;
                        //继续接收
                        state.buffer = new byte[StateObject.BufferSize];
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                        return;
                    }

                    //已经够读完了
                    Array.Copy(state.buffer, 0, state.totalBuffer, state.readBufferLength, state.totalLength - state.readBufferLength);

                    Console.WriteLine($"[{client.LocalEndPoint.ToString()}]接收包总长度[{state.totalLength}]字节数据");

                    UnPackageObject unPackageObject = MQPackageHelper.UnPackage(state.totalBuffer);

                    //接收成功事件不为null时触发
                    if (msgReceiveEvent != null)
                    {
                        Task.Run(() =>
                        {
                            msgReceiveEvent(unPackageObject);
                        });
                    }

                    //接收完完整的一个包,休息200毫秒  间隔太短可能导致实体类的值被覆盖
                    Thread.Sleep(200);

                    //继续接收这个客户端发来的下一个消息
                    StateObject nextState = new StateObject();
                    nextState.workSocket = client;
                    //当超出当前接收内容时触发
                    if (state.readBufferLength + bytesRead > state.totalLength)
                    {
                        //这里说明一个完整的消息体接收完了,有可能还会读到下一次的消息体
                        byte[] newTotalBuffer = new byte[state.readBufferLength + bytesRead - state.totalLength];
                        Array.Copy(state.buffer, state.totalLength - state.readBufferLength, newTotalBuffer, 0, state.readBufferLength + bytesRead - state.totalLength);
                        //要重新建一个对象,不然会影响到异步执行后续处理方法
                        nextState.readBufferLength = newTotalBuffer.Length;
                        if (nextState.readBufferLength >= 4)
                        {
                            //拼出消息体长度
                            byte[] totalLengthBytes = new byte[4];
                            Array.Copy(newTotalBuffer, 0, totalLengthBytes, 0, 4);
                            nextState.totalLength = ByteConvert.Bytes2UInt(totalLengthBytes);
                            nextState.totalBuffer = new byte[nextState.totalLength];
                        }
                        Array.Copy(newTotalBuffer, 0, nextState.totalBuffer, 0, nextState.readBufferLength);
                    }

                    client.BeginReceive(nextState.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), nextState);

                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }