如何在两台独立的计算机之间通过套接字传递数据

How pass data with socket between two separated computers

在我的工作中,我需要使用套接字从另一家公司获取数据,所以我首先尝试只使用我的电脑作为服务器和客户端。当我使用 localhost 或我的 IPv4 时一切正常,但是当我使用我的 public IP 时它崩溃并出现此错误:

the requested address is not valid in its context public

那么我怎样才能做到这一点?

这是我的代码

客户端

onnection:
        try
        {
            TcpClient client = new TcpClient("127.0.0.1", 1302);
            string messageToSend = "My name is Neo";

            int byteCount = Encoding.ASCII.GetByteCount(messageToSend + 1);
            byte[] sendData = new byte[byteCount];
            sendData = Encoding.ASCII.GetBytes(messageToSend);

            NetworkStream stream = client.GetStream();
            stream.Write(sendData, 0, sendData.Length);
            Console.WriteLine("Sending data to server...");

            StreamReader sr = new StreamReader(stream);
            string response = sr.ReadLine();
            Console.WriteLine(response);

            stream.Close();
            client.Close();
            Console.ReadKey();
        }catch(Exception e)
        {
            Console.WriteLine("Failed to connect...");
            goto connection;
        }

服务器

TcpListener listener = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 1302);
        listener.Start();
        while (true)
        {
            Console.WriteLine("Waiting for connection");
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client accepted");
            NetworkStream stream = client.GetStream();
            StreamReader sr = new StreamReader(client.GetStream());
            StreamWriter sw = new StreamWriter(client.GetStream());
            try
            {
                byte[] buffer = new byte[1024];
                stream.Read(buffer, 0, buffer.Length);
                int recv = 0;
                foreach(byte b in buffer)
                {
                    if(b != 0)
                    {
                        recv++;
                    }
                }
                string request = Encoding.UTF8.GetString(buffer, 0, recv);
                Console.WriteLine("request received: " + request);
                sw.WriteLine("Recibido");
                sw.Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong...");
                sw.WriteLine(e.ToString());
            }
        }

您似乎将环回地址 127.0.0.1 硬编码为所需的 IP 地址,但这在您自己的计算机之外不起作用。您应该在该特定端口上接受来自任何地址System.Net.IPAddres.Any 的 TCP 数据包。