+-

我有以下代码将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)和端口号上设置服务器以接受消息并回复?谢谢 :)
最佳答案
您需要一个
TcpListener对象才能充当服务器. TcpListener对象将侦听指定端口上的传入连接.您可以使用
.AcceptTcpClient方法建立新的连接. (如果您想要多个客户端,则必须研究多线程)
另外要注意的是,使用端口1将是一种不好的做法,通常为系统对象或标准协议(例如telnet,ftp,http等)保留低端口号.
点击查看更多相关文章
转载注明原文:C#-向IP地址和端口发送和接收TCP / IP消息 - 乐贴网