public int m_numConnectedSockets = 0; // the total number of clients connected to the server连接到服务器的客户端总数 private void ProcessSend(SocketAsyncEventArgs e) { MySocketEventArgs mys = (MySocketEventArgs)e; mys.IsUsing = false; //数据发送已完成.状态设为False Interlocked.Increment(ref m_numConnectedSockets); Console.WriteLine("客户端当前线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "已发送:" + m_numConnectedSockets); //Console.WriteLine("发送结束"); if (e.SocketError != SocketError.Success) { ProcessError(e); } }
/// <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); }
// Exchange a message with the host. internal void Send(IMessage message) { if (connected) { //先对数据进行包装,就是把包的大小作为头加入,这必须与服务器端的协议保持一致,否则造成服务器无法处理数据. byte[] sendBuffer = message.ToByteArray(); Console.WriteLine(sendBuffer.Length); 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); } bool willRaiseEvent = clientSocket.SendAsync(sendArgs); if (!willRaiseEvent)//当消息量小时 很可能会立即发送完毕 此时不会触发发送回调 必须要立即判断 { ProcessSend(sendArgs); } #region 测试protobuf 反序列化 //byte[] buff1 = new byte[sendBuffer.Length]; //Array.Copy(sendBuffer, 0, buff1, 0, 30); //CodedInputStream codedInputStream = new CodedInputStream(buff1); //int aaa = 1; //uint aaa1 = codedInputStream.ReadRawVarint32(ref aaa); //Person person = Person.Parser.ParseFrom(sendBuffer); //Console.WriteLine(person.Aliases); #endregion } else { throw new SocketException((Int32)SocketError.NotConnected); } }