Exemplo n.º 1
0
 void WriteY()
 {
     for (int i = 0; i < 100; i++)
     {
         byte         j     = (byte)i;
         MessageXieYi xieyi = new MessageXieYi(1, 0, new byte[5] {
             j, j, j, j, j
         });
         byte[] send   = xieyi.ToBytes();
         byte[] buffer = AsyncUserToken.GetSendBytes(send);
         SendSave(buffer);
     }
     Console.WriteLine("本次循环完成。");
 }
Exemplo n.º 2
0
    private void Send(AsyncUserToken userToken, byte[] send)
    {
        try
        {
            byte[] buffer = AsyncUserToken.GetSendBytes(send);
            //string sClientIP = ((IPEndPoint)userToken.ConnectSocket.RemoteEndPoint).ToString();
            //string info = "";
            //for (int i = 0; i < buffer.Length; i++)
            //{
            //    info += buffer[i] + ",";
            //}
            //Log4Debug("From the " + sClientIP + " to send " + buffer.Length + " bytes of data:" + info);

            //查找有没有空闲的发送MySocketEventArgs,有就直接拿来用,没有就创建新的.So easy!
            MySocketEventArgs sendArgs = null;
            lock (listArgs)//要锁定,不锁定让别的线程抢走了就不妙了.
            {
                sendArgs = listArgs.Find(a => a.IsUsing == false);
                if (sendArgs == null)
                {
                    sendArgs = initSendArgs();
                }
                sendArgs.IsUsing = true;
            }
            sendArgs.SetBuffer(buffer, 0, buffer.Length);
            sendArgs.UserToken = userToken;

            Socket s = userToken.ConnectSocket;
            if (!s.SendAsync(sendArgs))//投递发送请求,这个函数有可能同步发送出去,这时返回false,并且不会引发SocketAsyncEventArgs.Completed事件
            {
                // 同步发送时处理发送完成事件
                ProcessSend(sendArgs);
            }
        }
        catch (Exception e)
        {
            CloseClientSocket(userToken);
        }
    }