Ejemplo n.º 1
0
 public int Send(string IP_addr, int port, byte[] bytes, int length)//发送数据到客户端
 {
     IP_Port ip_port = new IP_Port(IP_addr, port);
     int index = clientArray.IndexOf(ip_port);//查找对应的客户端
     if (index == -1) return -1;
     Client client = (Client)clientArray[index];
     client.tcp_client.Client.Send(bytes, length, SocketFlags.None);//发送数据
     return length;
 }
Ejemplo n.º 2
0
 public ArrayList GetClientList()//获取客户端列表
 {
     ArrayList client_list = new ArrayList();
     IP_Port ip_port;
     if (clientArray.Count <= 0)
         return null;
     for (int i = 0; i < clientArray.Count; i++)
     {
         ip_port = new IP_Port(((Client)clientArray[i]).IP_addr, ((Client)clientArray[i]).Port);
         client_list.Add(ip_port);
     }
     return client_list;
 }
Ejemplo n.º 3
0
        private void AcceptMsg(object arg)//单个线程,循环读取数据
        {

            TcpClient client = (TcpClient)arg;
            NetworkStream ns = client.GetStream();
            int port;
            string IP_addr;
            port = (client.Client.RemoteEndPoint as IPEndPoint).Port;//获取连接的端口号 explain by LC 2014.07.22 16:54
            IP_addr = (client.Client.RemoteEndPoint as IPEndPoint).Address.ToString();//获取连接的IP号 explain by LC 2014.07.22 16:55

            while (bListening)
            {
                try
                {
                    /*不能直接使用client.Connected 或 client.Client.Connected判断连接状态,先使用client.Client.Poll*/
                    if (((client.Client.Poll(1000, SelectMode.SelectRead) && (client.Client.Available == 0)) || !client.Client.Connected)) 
                        throw new ApplicationException("与客户端连接断开");
                    byte[] bytes = new byte[1024];
                    int bytesread = ns.Read(bytes, 0, bytes.Length);//读取数据
                    if (bytesread == 0)
                    { 
                        continue;
                    }
                    OnRecieve(IP_addr, port, bytes, bytesread);
             //       msg = IP_addr + ":" + port + ":" + Encoding.Default.GetString(bytes, 0, bytesread);
                    ns.Flush();
                    
                  // client.Client.Send(bytes);//发送数据到客户端 explain by LC 2014.07.23 8:53
                }
                catch (Exception re)
                {
                  //  MessageBox.Show("与客户端断开连接了");
                  //  re = new Exception("与客户端断开连接了");
                    OnException(IP_addr, port, re);
                    IP_Port ip_port = new IP_Port(IP_addr, port);
                    clientArray.Remove(ip_port);//移除对应的IP和端口号
                    break;
                }
            }
            Thread.CurrentThread.Abort();//释放当前运行的线程
        }