扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:crystal编译 来源:yesky 2007年11月14日
关键字:
public void WaitingForClient() { while(true) { // Accept will block until someone connects Socket sckt = tcpLsn.AcceptSocket(); if (connectId < 10000) Interlocked.Increment(ref connectId); Else connectId = 1; if (socketHolder.Count < MaxConnected ) { while (socketHolder.Contains(connectId) ) { Interlocked.Increment(ref connectId); } Thread td = new Thread(new ThreadStart(ReadSocket)); lock(this) { // it is used to keep connected Sockets socketHolder.Add(connectId, sckt); // it is used to keep the active thread threadHolder.Add(connectId, td); } td.Start(); } } } // follow function handle the communication from the clients and close the // socket and the thread when the socket connection is down public void ReadSocket() { // the connectId is keeping changed with new connection added. it can't // be used to keep the real connectId, the local variable realId will // keep the value when the thread started. long realId = connectId; int ind=-1; Socket s = (Socket)socketHolder[realId]; while (true) { if(s.Connected) { Byte[] receive = new Byte[37] ; Try { // Receive will block until data coming // ret is 0 or Exception happen when Socket connection // is broken int ret=s.Receive(receive,receive.Length,0); if (ret > 0) { string tmp = null; tmp=System.Text.Encoding.ASCII.GetString(receive); if(tmp.Length > 0) { DateTime now1=DateTime.Now; String strDate; strDate = now1.ToShortDateString() + " " + now1.ToLongTimeString(); ListViewItem newItem = new ListViewItem(); string[] strArry=tmp.Split(':'); int code = checkUserInfo(strArry[0]); if(code==2) { userHolder.Add(realId, strArry[0]); newItem.SubItems.Add(strArry[0]); newItem.ImageIndex = 0; newItem.SubItems.Add(strDate); this.listView2.Items.Add(newItem); ind=this.listView2.Items.IndexOf(newItem); } else if( code==1) } } else { this.listView2.Items[ind].ImageIndex=1; keepUser=false; break; } } catch (Exception e) { if( !s.Connected ) { this.listView2.Items[ind].ImageIndex=1; keepUser=false; break; } } } } CloseTheThread(realId); } private void CloseTheThread(long realId) { socketHolder.Remove(realId); if(!keepUser) userHolder.Remove(realId); lock(this) { Thread thd = (Thread)threadHolder[realId]; threadHolder.Remove(realId); } thd.Abort(); } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者