我有以下代码将 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”传递。当方法执行时,我得到以下异常:
发生这种情况是因为另一端没有人在听吗?如果是,我如何在该 IP 地址(好的,不是 0.0.0.45 而是 127.0.0.1)和端口号设置服务器以接受消息并回复它?谢谢 :)