接受客户端 Start
功能只会启动...而且永远不会结束
void Start(){
StartListening();//when the server starting
}
void StartListening(){
server.BeginAcceptTcpClient (AcceptTcpClient,server);
}
void AcceptTcpClient(IAsyncResult ar){
TcpListener listener = (TcpListener)ar.AsyncState;
clients.Add (new ServerClient (listener.EndAcceptTcpClient (ar)));
StartListening ();
}
侦听客户端 Update
函数将每毫秒运行一次。
void Update(){ foreach (ServerClient c in clients.ToList()) {
//is the client still connected
if (!isConnected (c.tcp)) {
c.tcp.Close ();
disconnectList.Add (c);
continue;
} else {
NetworkStream s = c.tcp.GetStream ();
if(s.DataAvailable){
StreamReader reader = new StreamReader (s,true);
string data = reader.ReadLine ();
if (data != null)
OnIncomingData (c,data);
}
}
}}
这不是完全代码,但我认为它足以理解我的问题。问题是服务器代码可以同时处理多个客户端吗? ..或者在连接或从服务器接收时会冻结。
P.S
private bool isConnected(TcpClient c){
try{
if(c!=null && c.Client!=null && c.Client.Connected){
if(c.Client.Poll(0,SelectMode.SelectRead)){
return !(c.Client.Receive(new byte[1],SocketFlags.Peek)==0);
}
return true;
}else {
return false;}
}
catch {
return false;
}
}