Beispiel #1
0
        public void Send(AsyncUserToken userToken, byte[] buffer)
        {
            //查找有没有空闲的发送MySocketEventArgs,有就直接拿来用,没有就创建新的.So easy!
            MySocketEventArgs sendArgs = null;

            lock (listArgs)
            {
                sendArgs = listArgs.Find(a => a.IsUsing == false);
                if (sendArgs == null)
                {
                    sendArgs = initSendArgs();
                }
                sendArgs.IsUsing = true;
            }

            //Log4Debug("发送所用的套接字编号:" + sendArgs.ArgsTag);
            //lock (sendArgs) //要锁定,不锁定让别的线程抢走了就不妙了.
            {
                sendArgs.SetBuffer(buffer, 0, buffer.Length);
            }
            Socket s = userToken.ConnectSocket;

            if (!s.SendAsync(sendArgs))//投递发送请求,这个函数有可能同步发送出去,这时返回false,并且不会引发SocketAsyncEventArgs.Completed事件
            {
                // 同步发送时处理发送完成事件
                ProcessSend(sendArgs);
            }
        }
Beispiel #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);
        }
    }