我有以下的代碼,將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'傳遞。當該方法執行,我得到以下異常:
這是happenning因爲沒有一個在另一端聽嗎?如果是的話,我該如何在該IP地址(ok,不是0.0.0.45,但是127.0.0.1)和端口號上設置服務器來接受消息並回復它?謝謝:)
看看'TcpListener'類。 –
謝謝Jon Skeet :) – Matthew