private void ProcessAccept(SocketAsyncEventArgs e)
{
if (e.LastOperation != SocketAsyncOperation.Accept)//检查上一次操作是否是Accept,不是就返回
return;
string UID = GetIDByIP((e.AcceptSocket.RemoteEndPoint as IPEndPoint).Address.ToString());//根据IP获取用户的UID
try
{
if (e.SocketError == SocketError.Success)
{
if (string.IsNullOrEmpty(UID)) //判断现在的用户是否已经连接,避免同一用户开两个连接
return;
if (readWritePool.BusyPoolContains(UID))
return;
SocketAsyncEventArgsWithId readEventArgsWithId = this.readWritePool.Pop(UID);
readEventArgsWithId.ReceiveSAEA.UserToken = e.AcceptSocket;
readEventArgsWithId.SendSAEA.UserToken = e.AcceptSocket;
Interlocked.Increment(ref this.numConnections);//修改连接数
//侦听到客户端连接开始接受数据(我是不是需要在这儿开个线程来接收数据)
Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgsWithId.ReceiveSAEA);
if (!willRaiseEvent)
{
this.ProcessReceive(readEventArgsWithId.ReceiveSAEA);
}
}
else
{
CloseClientSocket(UID);
}
}
catch (Exception)
{
CloseClientSocket(UID);
}
finally
{
this.StartAccept(e);
}
}
private void
ProcessReceive(SocketAsyncEventArgs e)
{
if
(e.LastOperation != SocketAsyncOperation.Receive)
return
;
if
(e.BytesTransferred > 0)
{
if
(e.SocketError == SocketError.Success)
{
Int32 byteTransferred = e.BytesTransferred;
string
received = Encoding.Unicode.GetString(e.Buffer, e.Offset,byteTransferred);
if(ms.Read(out socketHander)//ms是以流的方式对数据进行验证,返回一个socketHander对象,并且ms是针对每一个客户端创建的
{
OnMsgReceived(((MySocketAsyncEventArgs)e).UID, socketHander);
}
Boolean willRaiseEvent = (e.UserToken
as
Socket).ReceiveAsync(e);
if
(!willRaiseEvent)
ProcessReceive(e);
}
}
else
this
.CloseClientSocket(((MySocketAsyncEventArgs)e).UID);
}
现在的问题是多人同时发送文件时,后面一个连接的会把前面一个建立的连接给停止掉..我这个方法是不是要加线程.来处理数据?
来结贴啦哈哈~~~
楼主+我QQ