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. 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.
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. Not 192.168.1.59, but:
static void Main(string[] args) {
IPAddress ip = IPAddress.Parse("172.17.xx.xx");
...