Beispiel #1
0
        // Exchange a message with the host.
        internal void Send(byte[] sendBuffer)
        {
            if (_connected)
            {
                //先对数据进行包装,就是把包的大小作为头加入,这必须与服务器端的协议保持一致,否则造成服务器无法处理数据.
                var buff = new byte[sendBuffer.Length + 4];
                Array.Copy(BitConverter.GetBytes(sendBuffer.Length), buff, 4);
                Array.Copy(sendBuffer, 0, buff, 4, sendBuffer.Length);

                //查找有没有空闲的发送MySocketEventArgs,有就直接拿来用,没有就创建新的.So easy!
                MySocketEventArgs sendArgs = _listArgs.Find(a => a.IsUsing == false) ?? InitSendArgs();

                lock (sendArgs) //要锁定,不锁定让别的线程抢走了就不妙了.
                {
                    sendArgs.IsUsing = true;
                    sendArgs.SetBuffer(buff, 0, buff.Length);
                }

                _clientSocket.SendAsync(sendArgs);
            }
            else
            {
                //throw new SocketException((int)SocketError.NotConnected);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 初始化发送参数MySocketEventArgs
        /// </summary>
        /// <returns></returns>
        MySocketEventArgs InitSendArgs()
        {
            var sendArg = new MySocketEventArgs();

            sendArg.Completed     += IO_Completed;
            sendArg.UserToken      = _clientSocket;
            sendArg.RemoteEndPoint = _hostEndPoint;
            sendArg.IsUsing        = false;
            Interlocked.Increment(ref _tagCount);
            sendArg.ArgsTag = _tagCount;
            lock (_listArgs)
            {
                _listArgs.Add(sendArg);
            }

            return(sendArg);
        }