简体   繁体   English

在我的计算机上将 VM 客户端连接到服务器 C#

[英]Connecting VM Client To Server On My Computer C#

I'm having trouble with this network chat application code I found.我发现这个网络聊天应用程序代码有问题。 It works fine when both applications are run on the same computer, but when trying to connect a VM client to my host app running on my real install, I get a timeout.当两个应用程序在同一台计算机上运行时,它工作正常,但是当尝试将 VM 客户端连接到在我的真实安装上运行的主机应用程序时,我得到了超时。 Here is the code.这是代码。

static readonly object _lock = new object();
        static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();

        static void Main(string[] args) {
            int count = 1;

            TcpListener ServerSocket = new TcpListener(IPAddress.Parse("192.168.1.59"), 5000);
            ServerSocket.Start();

            while(true) {
                TcpClient client = ServerSocket.AcceptTcpClient();
                lock(_lock) list_clients.Add(count, client);
                Console.WriteLine("Someone connected!!");

                Thread t = new Thread(handle_clients);
                t.Start(count);
                count++;
            }
        }
    }

class Client {
        static void Main(string[] args) {
            IPAddress ip = IPAddress.Parse("192.168.1.59");
            int port = 5000;
            TcpClient client = new TcpClient();
            client.Connect(ip, port);
            Console.WriteLine("client connected!!");
            NetworkStream ns = client.GetStream();
            Thread thread = new Thread(o => ReceiveData((TcpClient)o));

            thread.Start(client);

            string s;
            while(!string.IsNullOrEmpty((s = Console.ReadLine()))) {
                byte[] buffer = Encoding.ASCII.GetBytes(s);
                ns.Write(buffer, 0, buffer.Length);
            }

            client.Client.Shutdown(SocketShutdown.Send);
            thread.Join();
            ns.Close();
            client.Close();
            Console.WriteLine("disconnect from server!!");
            Console.ReadKey();
        }
    }```

Your VM is probably running in a different network interface.您的 VM 可能在不同的网络接口中运行。

Try instead:改为尝试:

TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);

This way you tell the server to listen on any network interface.这样,您就可以告诉服务器在任何网络接口上进行侦听。

Addition: Also, the VM client should connect to the IP address your computer (with TCPListener program) has, within the VM network range.另外:此外,VM 客户端应连接到您的计算机(带有 TCPListener 程序)在 VM 网络范围内的 IP 地址。 Not 192.168.1.59, but:不是 192.168.1.59,而是:

static void Main(string[] args) {
    IPAddress ip = IPAddress.Parse("172.17.xx.xx");
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM