我有以下代码,用于向特定的IP地址和端口发送TCP/IP消息:
现在假设我将IP地址设置为“127.0.0.1”,端口设置为“1”。当方法执行时,我会得到以下异常:
这是因为没有其他人在监听吗?如果是这样的话,我如何在那个IP地址(不是0.0.0.45而是127.0.0.1)和端口号上设置一个服务器来接受并回复消息呢?谢谢 :)
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地址设置为“127.0.0.1”,端口设置为“1”。当方法执行时,我会得到以下异常:
![enter image description here](https://istack.dev59.com/Z8K2V.webp)
TcpListener
类。 - Jon Skeet