C# - 向 IP 地址和端口发送和接收 TCP/IP 消息

2023-12-31

我有以下代码将 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 http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx对象充当服务器。这TcpListener对象将侦听指定端口上的传入连接。您可以使用.AcceptTcpClient http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient.aspx建立新连接的方法。 (如果您想要多个客户端,则必须考虑多线程)

另外,使用端口 1 是一种不好的做法,低端口号通常保留给系统内容或标准协议,例如telnet, ftp, http etc.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# - 向 IP 地址和端口发送和接收 TCP/IP 消息 的相关文章

随机推荐