C# - 发送和接收TCP / IP消息发送到IP地址和端口 [英] C# - Sending and Receiving a TCP/IP message to an IP Address and Port
问题描述
我有以下代码发送一个TCP / IP消息发送到一个特定的IP地址和端口:
I have the following code to send a TCP/IP message to a specific IP Address and Port:
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'。当方法执行,我得到了以下异常:
Now, let us assume that I pass the ip_address as '127.0.0.1' and the port as '1'. When the method executes, I am getting the following exception:
这是因为happenning有没有人在另一端听吗?如果是的话,我怎么能建立一个服务器在该IP地址(好吧,不0.0.0.45但127.0.0.1)和端口号来接受和回复信息呢?谢谢:)
Is this happenning because there is no one listening at the other end? If yes, how can I set up a server at that ip address (ok, not 0.0.0.45 but 127.0.0.1) and port number to accept the message and reply to it? Thank you :)
推荐答案
您会需要的 的TcpListener
对象作为服务器行事。在的TcpListener
对象将侦听指定端口上的连接。您可以使用 。 AcceptTcpClient
方法来建立一个新的连接。 (如果你想多个客户端,你不得不考虑多线程)
You'd need a TcpListener
object to act as the server. The TcpListener
object would listen for incoming connections on the specified port. You can use the .AcceptTcpClient
method to establish a new connection. (If you wanted multiple clients you'd have to look into multithreading)
此外,使用端口1将是不好的做法一个侧面说明,低端口号通常保留给系统的东西或标准协议,如远程登录
, FTP
, HTTP
等
Also as a side note using Port 1 would be bad practice, low port numbers are usually reserved for system stuff or standard protocols such as telnet
, ftp
, http
etc.
这篇关于C# - 发送和接收TCP / IP消息发送到IP地址和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!