Ejemplo n.º 1
0
 private void listen()
 {
     try
     {
         server.Listen(maxListen);
         while (isListen)
         {
             Socket     cs        = server.Accept();
             IPEndPoint clientipe = (IPEndPoint)cs.RemoteEndPoint;
             userListDelegate.Invoke("add|" + clientipe.Address.ToString() + ":" + clientipe.Port.ToString());
             Socket agentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             agentSocket.Connect(new IPEndPoint(IPAddress.Parse(address), agentPort));
             AgentObj agent = new AgentObj();
             agent.socket      = cs;
             agent.agnetSocket = agentSocket;
             addAgent(agent);
             new Thread(receive).Start(agent);
             new Thread(response).Start(agent);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("服务异常");
     }
     finally {
         if (null != server)
         {
             server.Close();
         }
     }
 }
Ejemplo n.º 2
0
 private void  closeAgent(AgentObj obj)
 {
     lock (socketObj)
     {
         try
         {
             if (null != obj)
             {
                 if (null != obj.socket)
                 {
                     IPEndPoint clientipe = (IPEndPoint)obj.socket.RemoteEndPoint;
                     userListDelegate.Invoke("remove|" + clientipe.Address.ToString() + ":" + clientipe.Port.ToString());
                     obj.socket.Close();
                 }
                 if (null != obj.agnetSocket)
                 {
                     obj.agnetSocket.Close();
                 }
                 if (users.Contains(obj))
                 {
                     users.Remove(obj);
                 }
             }
         }
         catch (Exception e)
         {
         }
     }
 }
Ejemplo n.º 3
0
        private void receive(object o)
        {
            AgentObj agent = (AgentObj)o;

            byte[] buffer = new byte[1024];
            int    temp   = -1;

            while (true)
            {
                try
                {
                    temp = agent.socket.Receive(buffer);
                    if (temp <= 0)
                    {
                        throw new IOException("连接已关闭");
                    }
                    agent.agnetSocket.Send(buffer, 0, temp, SocketFlags.None);
                }
                catch (Exception e) {
                    Console.WriteLine(e.ToString());
                    closeAgent(agent);
                    break;
                }
            }
        }
Ejemplo n.º 4
0
 private void addAgent(AgentObj obj)
 {
     lock (socketObj) {
         users.Add(obj);
     }
 }