Ejemplo n.º 1
0
 // Exchange a message with the host.
 internal void Send(byte[] sendBuffer)
 {
     if (connected)
     {
         //先对数据进行包装,就是把包的大小作为头加入
         byte[] buff = new byte[sendBuffer.Length + 4];
         Array.Copy(BitConverter.GetBytes(Overall.CryString.Length), buff, 4);
         Array.Copy(sendBuffer, 0, buff, 4, sendBuffer.Length);
         //查找有没有空闲的发送MySocketEventArgs
         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);
     }
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 3
0
        void IO_Completed(object sender, SocketAsyncEventArgs e)
        {
            MySocketEventArgs mys = (MySocketEventArgs)e;

            // determine which type of operation just completed and call the associated handler
            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");
            }
        }