Java Chat with TCP/IP over LAN

2020-04-19 05:48发布

问题:

I have developed an application for chatting using TCP/IP in Java. So far it does the job when running the server and clients on the same machine, however I want to make it work over LAN.

I have found out that I shall be using port forwarding on my router, for the same port that I am using in the clients & server and forward it to IP of my machine (that will be the server). Also I found out that I shall be careful of the firewalls.

On my virgin media hub router I have port forwarded the port im using (4444), with protocol TCP to the local IP of my machine (192.168.0.21). I have also made sure that no port is blocked.

For firewalls, I have made sure that the windows firewall is not enabled and switched off my kaspersky anti-virus firewall.

So far this didn't allow me yet to have a communication over the LAN, with my vmware machine.

Here is the code for socket and server socket;

Client:

int portNumber = 4444;
InetAddress host = InetAddress.getLocalHost(); // I also did try changing the host to a String and making host = InetAddress.getLocalHost().getHostAddress();
Socket link = new Socket(host, portNumber);

Server:

int portNumber = 4444;
ServerSocket serverSocket = new ServerSocket(portNumber);
link = serverSocket.accept();

Any idea what I'm doing wrong, or missing something?

回答1:

With that code (InetAddress host = InetAddress.getLocalHost();) your clientside will always contact localhost, and that's obviously not what you want (but an explanation why it works locally...

May I suggest the official Oracle tutorial on client-server communication?

Assuming your remote system's IP address is 192.168.0.100, your code will be

int portNumber = 4444;
String host = "192.168.0.100"; // Socket also has a constructor that accepts
                               // as String where you can either input a hostname or
                               // an IP address
Socket link = new Socket(host, portNumber);

Socket Javadoc here

EDIT: the major flaw in your program is that you use InetAddress.getLocalHost() which according to the Javadoc

Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.

Emphasis mine. So yes, your program will work with the local computer but not with remote computers. The essential of my answer is not that I use a String, but that I don't use localhost...