2013-07-01 174 views
2

我有以下的代碼,將TCP/IP消息到特定的IP地址和端口:C# - 發送和接收TCP/IP消息的IP地址和端口

public bool sendTCPMessage(string ip_address, string port, string transaction_id, string customer_username, DateTime date) 
     { 
      bool success = false; 

      try 
      { 
       int converted_port = Convert.ToInt32(port); 
       string converted_date = date.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); 

       JObject obj = new JObject(); 
       obj["Transaction_Status"] = "Paid"; 
       obj["Transaction_ID"] = transaction_id; 
       obj["Processed_Date"] = converted_date; 
       obj["Customer_Username"] = customer_username; 

       JSONMobile json_mobile = new JSONMobile(); 
       string json = json_mobile.SerializeToString(obj); 

       TcpClient client = new TcpClient(ip_address, converted_port); 
       Byte[] message = System.Text.Encoding.ASCII.GetBytes(json); 
       NetworkStream stream = client.GetStream(); 
       stream.Write(message, 0, message.Length); 
       stream.Close(); 
       client.Close(); 

       success = true; 
      } 
      catch (Exception) 
      { 
       success = false; 
      } 
      return success; 
     } 

現在,讓我們假設我將ip_address作爲'127.0.0.1'並將端口作爲'1'傳遞。當該方法執行,我得到以下異常:

enter image description here

這是happenning因爲沒有一個在另一端聽嗎?如果是的話,我該如何在該IP地址(ok,不是0.0.0.45,但是127.0.0.1)和端口號上設置服務器來接受消息並回復它?謝謝:)

+1

看看'TcpListener'類。 –

+0

謝謝Jon Skeet :) – Matthew

回答

2

你需要一個TcpListener對象作爲服務器。 TcpListener對象將偵聽指定端口上的傳入連接。您可以使用.AcceptTcpClient方法建立新的連接。 (如果你想多個客戶端,你不得不考慮多線程)

另外,作爲使用端口1將是不好的做法一個側面說明,低端口號通常保留給系統的東西或標準協議,如telnetftphttp

+0

謝謝達倫:)我會試試你的建議:) – Matthew