【问题标题】:C# - Sending and Receiving a TCP/IP message to an IP Address and PortC# - 向 IP 地址和端口发送和接收 TCP/IP 消息
【发布时间】:2013-06-28 07:51:57
【问题描述】:

我有以下代码将 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类。

标签: c# tcp port ip-address


【解决方案1】:

您需要一个TcpListener 对象来充当服务器。 TcpListener 对象将侦听指定端口上的传入连接。您可以使用.AcceptTcpClient 方法建立新连接。 (如果您想要多个客户端,则必须考虑多线程)

另外,使用端口 1 是不好的做法,低端口号通常保留给系统内容或标准协议,例如 telnetftphttp 等。

【讨论】:

  • 谢谢达伦 :) 我会试试你的建议 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2011-09-13
  • 1970-01-01
  • 2012-10-17
  • 2010-11-17
  • 2017-10-24
相关资源
最近更新 更多