Socket socketWitch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                IPEndPoint iep = new IPEndPoint(ip, Convert.ToInt32(txtport.Text));
                socketWitch.Bind(iep);//绑定监听端口
                socketWitch.Listen(10);//设置监听队列
                MesShow("监听成功");

                Thread th = new Thread(SocketListen);
                th.IsBackground = true;
                th.Start(socketWitch);

 

 

public void SocketListen(object sw)
        {
            
            Socket socketWitch = sw as Socket;
            while (true)
            {
                try
                {
                    
                    socketSend = socketWitch.Accept();//创建链接循环等待客户端链接
                    MesShow(socketSend.RemoteEndPoint.ToString()+"链接成功");
                    dic.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    cobclient.Items.Add(socketSend.RemoteEndPoint);

                    Thread th = new Thread(ReceiveStr);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch { }
            }
        }

 

 

 public void ReceiveStr(object ss)
        {
            while (true)
            {
                try
                {
                    Socket socketSend = ss as Socket;
                    byte[] by = new byte[1024 * 1024 * 2];
                    int i = socketSend.Receive(by);
                    if (i == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(by, 0, i);
                    MesShow(socketSend.RemoteEndPoint.ToString() + ":" + str);
                }
                catch
                { }
            }
        }

 

 posted on 2015-04-01 10:49  阿曜  阅读(128)  评论(0编辑  收藏  举报