【问题标题】:Connecting VM Client To Server On My Computer C#在我的计算机上将 VM 客户端连接到服务器 C#
【发布时间】:2020-06-01 07:20:54
【问题描述】:

我发现这个网络聊天应用程序代码有问题。当两个应用程序在同一台计算机上运行时,它工作正常,但是当尝试将 VM 客户端连接到在我的真实安装上运行的主机应用程序时,我得到了超时。这是代码。

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();
        }
    }```

【问题讨论】:

    标签: c# server client tcplistener


    【解决方案1】:

    您的虚拟机可能在不同的网络接口中运行。

    试试吧:

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

    这样你告诉服务器监听任何网络接口。

    补充:另外,VM 客户端应该连接到您的计算机(使用 TCPListener 程序)在 VM 网络范围内的 IP 地址。不是 192.168.1.59,而是:

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

    【讨论】:

    • 刚试了下还是超时。 IPConfig 显示虚拟机是 172.17.158.37,所以我认为您对网络范围的看法可能是正确的。这到底是怎么回事?
    • VM 客户端应该连接到您的计算机(使用 TCPListener 程序)在 VM 网络范围内的 IP 地址。这将在 172.17 ... 的行中,而不是 192.168.1.59
    • 我不确定我是否完全理解。需要改变什么?
    • 客户端代码:static void Main(string[] args) { IPAddress ip = IPAddress.Parse("172.17.xx.xx");
    • 我仍然无法让它工作。有什么办法可以将 Hyper-V 配置为不这样做吗?据我所知,在我运行的服务器上,IP 分配正常。
    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多