C# - Sending and Receiving a TCP/IP message to an

2019-02-18 20:50发布

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;
        }

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:

enter image description here

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 :)

1条回答
够拽才男人
2楼-- · 2019-02-18 21:07

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)

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.

查看更多
登录 后发表回答