Example #1
0
        //与主机交换消息。
        public void Send(byte[] sendBuffer)
        {
            if (connected)
            {
                //先对数据进行包装,就是把包的大小作为头加入,这必须与服务器端的协议保持一致,否则造成服务器无法处理数据.
                byte[] 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);
                if (sendArgs == null)
                {
                    sendArgs = initSendArgs();
                }
                lock (sendArgs) //要锁定,不锁定让别的线程抢走了就不妙了.
                {
                    sendArgs.IsUsing = true;
                    sendArgs.SetBuffer(buff, 0, buff.Length);
                }
                clientSocket.SendAsync(sendArgs);
            }
            else
            {
                throw new SocketException((Int32)SocketError.NotConnected);
            }
        }
Example #2
0
        /// <summary>
        /// 初始化发送参数MySocketEventArgs
        /// </summary>
        /// <returns></returns>
        MySocketEventArgs initSendArgs()
        {
            MySocketEventArgs sendArg = new MySocketEventArgs();

            sendArg.Completed     += new EventHandler <SocketAsyncEventArgs>(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);
        }
Example #3
0
        void IO_Completed(object sender, SocketAsyncEventArgs e)
        {
            MySocketEventArgs mys = (MySocketEventArgs)e;

            //确定刚刚完成的操作类型并调用关联的处理程序
            switch (e.LastOperation)
            {
            case SocketAsyncOperation.Receive:
                ProcessReceive(e);
                break;

            case SocketAsyncOperation.Send:
                mys.IsUsing = false;     //数据发送已完成.状态设为False
                ProcessSend(e);
                break;

            default:
                throw new ArgumentException("The last operation completed on the socket was not a receive or send");
            }
        }