2017-01-30 91 views
0

情景:C#,TcpClient的多個IP地址,但在同一端口上

我有多個機器,每個機智命中自己的IP,運行一個TCPSERVER,所有在同一端口上。在每個事務中,如果打開了tcpServer端口,則會發送數據。它在開放港口之前尋找客戶。

我需要什麼:

我正在寫一個應用程序,需要:通過IP的名單,如果他們是菱 1.檢查 2.打開一個TcpClient的端口,每臺機器的IP,(全在相同的端口上) 3.每隔指定的時間後,確保連接處於打開狀態,如果沒有重新打開連接。

未來:

我使用XML文件,得到用於獲取計算機列表和端口上偵聽的SQL數據。在這個xml中也是一個udp設置,如果是,那麼發送的數據必須被接收並重定向到指定的UDP端口。

的類別:

public static void tcpListen(IPAddress server, int port) 
     { 
      try 
      { 
       TcpListener listener = new TcpListener(server, port); 
       listener.AcceptTcpClient(); 
       listener.Start(); 

       while (true) 
       { 
        Socket client = listener.AcceptSocket(); 

        var childSocketThread = new Thread(() => 
        { 
         byte[] data = new byte[100]; 
         int size = client.Receive(data); 
         for (int i = 0; i < size; i++) 
         feedback = server + ":" + port + ": " + Convert.ToChar(data[i]); 

         using (StreamWriter w = File.AppendText("TCPLog.log")) 
         { 
          Log(feedback, w); 
         } 
         client.Close(); 
        }); 
        childSocketThread.Start(); 
       } 
      } 
      catch (Exception err) 
      { 
       using (StreamWriter w = File.AppendText("error.log")) 
       { 
        Log("tcpControl.tcpListen: " + err.Message, w); 
       } 
      } 
     } 

代碼,每幾秒鐘重複部分:

private void ptoCheck() 
     { 
      IPAddress sourceIP; 
      int sourcePort; 
      int destinationPort; 
      string tcpStatus; 
      int oldCOunt = dgvWorkstations.RowCount; 
      int newCount = sqlScripts.posCount(sqlServer, sqlUser, sqlPassword, sqlDatabase); 

      if (newCount != oldCOunt) 
      { 
       getWorkstations(); 
      } 

      try 
      { 
       foreach (DataGridViewRow row in dgvWorkstations.Rows) 
       { 
        int i = row.Index; 
        bool tcpState; 
        dgvWorkstations["Status", i].Value = "Checking"; 
        dgvWorkstations.Refresh(); 
        name = row.Cells["POS_Name"].Value.ToString(); 
        sourceIP = IPAddress.Parse(row.Cells["LastKnownIP"].Value.ToString()); 
        sourcePort = Convert.ToInt32(row.Cells["Receive_Port"].Value.ToString()); 
        destinationPort = Convert.ToInt32(row.Cells["Send_Port"].Value.ToString()); 
        tcpState = tcpControl.tcpCheck(sourceIP, sourcePort, name); 

        if (tcpState == false) 
        { 
         dgvWorkstations["Status", i].Value = "Connecting";       
         dgvWorkstations.Refresh(); 
         tcpStatus = tcpControl.tcpConnect(sourceIP, sourcePort, name); 
         tcpControl.tcpListen(sourceIP, sourcePort); 
         dgvWorkstations["Status", i].Value = tcpStatus; 
        } 

        if (tcpState == true) 
        { 
         dgvWorkstations["Status", i].Value = "Connected"; 
         dgvWorkstations.Refresh(); 
        } 
        i = i + 1; 
       } 
      } 
      catch (Exception err) 
      { 
       using (StreamWriter w = File.AppendText("AError.log")) 
       { 
        Log("frmMain.ptoCheck: (" + name + ") " + err.Message, w); 
       } 
      }//End Catch 
     } 
+0

嘗試使用線程或backgroundworkers。我們可以看到你使用的代碼嗎? – Sergio

+0

可以只有一個IP連接具有相同的3個參數:1)源IP地址,2)目標IP地址3)端口號。當客戶端和服務器在同一臺PC上時,客戶端連接到計算機的IP地址,服務器端會偵聽到IPAny,因此不會有任何衝突。當在單臺PC上模擬網絡時,您需要多個網卡,以便您擁有更多而不是一個IP地址,否則,您需要使用不同的端口號。 – jdweng

+0

我試圖添加我用於連接的代碼,但它一直顯示錯誤,並說太多字符。 – shinga77

回答

0

我得到了下面的代碼頭工作,從我的課,我可以現在做多個連接,然而。我調用另一個方法來偵聽和接收數據的部分阻止了第一種方法,並保持它直到連接斷開而不進行進一步的連接。

我的班級:

public void tcpTest2(IPAddress server, Int32 port, int x) 
     { 
      TcpClient client; 

      sendData("Connecting to Host: " + server + " on port: " + port.ToString() + "..."); 
      sendStatus("Connecting", x); 

      try 
      { 
       client = new TcpClient(server.ToString(), port); 

       if (false) 
       { 

       }    

       if (true) 
       { 
        sendData("Connection to Host: " + server + " on port: " + port.ToString() + "..ESTABLISHED"); 
        sendStatus("Connected", x);   
        receiveData(client, server, port); 
       } 

      } 
      catch (Exception) 
      { 
       sendData("Connection to Host: " + server + " on port: " + port.ToString() + "..FAILED"); 
       sendStatus("Failed", x); 
      } 
     } 

     public void receiveData(TcpClient client, IPAddress server, int port) 
     { 
      Byte[] data = System.Text.Encoding.Default.GetBytes("|"); 
      data = new byte[1024]; 
      string stringData; 
      bool connected; 
      connected = true; 

      while (connected == true) 
      { 
       string fromC = client.Client.RemoteEndPoint.ToString(); 
       NetworkStream ns = client.GetStream(); 
       int recv = ns.Read(data, 0, data.Length); 
       stringData = Encoding.ASCII.GetString(data, 0, recv); 
       sendUpdate("{" + fromC + "}" + stringData); 
       connected = IsConnected(client); 
      } 

      if (connected == false) 
      { 
       sendData("Connection to Host: " + server + " on port: " + port.ToString() + "..LOST"); 
       sendLost(server); 
      } 
     } 

     public bool IsConnected(TcpClient client) 
     { 
      try 
      { 
       if (client != null && client.Client != null && client.Client.Connected) 
       { 
        if (client.Client.Poll(0, SelectMode.SelectRead)) 
        { 
         byte[] buff = new byte[1]; 
         if (client.Client.Receive(buff, SocketFlags.Peek) == 0) 
         { 
          return false; 
         } 
         else 
         { 
          return true; 
         } 
        } 

        return true; 
       } 
       else 
       { 
        return false; 
       } 
      } 
      catch 
      { 
       return false; 
      } 
     } 
    }  
0

這裏是爲我工作的最終代碼:

我的班級:

public void tcpConnect(object pos) 
     { 
      IPAddress hostIP = IPAddress.Parse(pos.ToString().Split(':')[0]); 
      int hostPort = Int32.Parse(pos.ToString().Split(':')[1]); 
      rowInd = Int32.Parse(pos.ToString().Split(':')[2]); 

      var client = new TcpClient();    

      if (!client.ConnectAsync(hostIP, hostPort).Wait(1000)) 
      { 
       sendData("Connection to Host: " + hostIP + " on port: " + hostPort.ToString() + ".FAILED"); 
       sendStatus("Failed", "", rowInd); 
       return; 
      } 

      if (true) 
      { 
       sendData("Connection to Host: " + hostIP.ToString() + " on port: " + hostPort.ToString() + "..ESTABLISHED"); 
       Thread thread = new Thread(new ParameterizedThreadStart(ClientHandler)); 
       thread.IsBackground = true; 
       Thread.FreeNamedDataSlot(hostIP.ToString() + rowInd.ToString()); 
       thread.Name = hostIP.ToString() + rowInd.ToString(); 
       thread.Start(client); 
       threadID = thread.ManagedThreadId.ToString(); 
       sendStatus("Connected", threadID, rowInd); 
      } 
     } 

     public bool IsConnected(TcpClient client) 
     { 
      try 
      { 
       if (client != null && client.Client != null && client.Client.Connected) 
       { 
        if (client.Client.Poll(0, SelectMode.SelectRead)) 
        { 
         byte[] buff = new byte[1]; 
         if (client.Client.Receive(buff, SocketFlags.Peek) == 0) 
         { 
          return false; 
         } 
         else 
         { 
          return true; 
         } 
        } 

        return true; 
       } 
       else 
       { 
        return false; 
       } 
      } 
      catch 
      { 
       return false; 
      } 
     } 

     public void ClientHandler(object c) 
     {    
      TcpClient client = (TcpClient)c;    
      NetworkStream netstream = client.GetStream(); 
      string fromC = client.Client.RemoteEndPoint.ToString(); 
      string fromIP = fromC.Split(':')[0]; 

      bool connected = true; 
      while (connected) 
      { 
       Thread.Sleep(10); 
       try 
       { 
        byte[] data = new byte[client.ReceiveBufferSize]; 
        data = System.Text.Encoding.Default.GetBytes("|"); 
        data = new byte[1024]; 
        string stringData;     
        NetworkStream ns = client.GetStream(); 
        int recv = ns.Read(data, 0, data.Length); 
        stringData = Encoding.ASCII.GetString(data, 0, recv); 
        sendUpdate("|" + fromC + "|" + stringData); 
        connected = IsConnected(client); 
       } 
       catch (Exception err) 
       { 
        connected = false; 
        sendLost(fromIP); 

        using (StreamWriter w = File.AppendText("Arch-PTO.log")) 
        { 
         Log("tcpServices.ClientHandler: " + err.Message, w); 
        } 
       } 
      }    
      sendLost(fromIP); 
     }