// Exchange a message with the host. internal 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); } }
/// <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); }
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"); } }