简体   繁体   中英

Java: Server/Client -> Client/Client

I want to set-up a peer to peer connection between some computers, so users can chat and exchange files without an external Server. My first thoughts were as follows:

I make a central ServerSocket on a server, where all applications can connect to. This ServerSocket keeps track of the connected sockets (clients), and gives the IP and Port of a new connected client to all other clients. Each client creates a new ServerSocket to which all clients can connect to.

在此处输入图片说明

In other words: every client has a ServerSocket with all other clients connected to it. The messages should go via the blue lines in the images.

There is just one little problem I run on: if I test this via all different IP addresses, it works fine, but when two clients have the same (external) IP-adress, it doesn't work any more. Does someone know a smart solution for this?

Thanks! Marc

When a host is behind a NAT router and wants to open a server port which is supposed to be accessible from the other side of the NAT, the NAT router has to be configured to forward all incomming connections on this port to this host.

Obviously, the NAT router can't be configured to do this for two different hosts which listen to the same port. It can't know which of the hosts is supposed to handle each incomming connection. When there are two servers behind a NAT, they have to use different ports, and the NAT router has to be configured to forward each port to each server.

This is a known problem for peer-to-peer networks. Its result is that a direct connection between two clients which are both behind NATs is only possible when at least one of their NATs is configured for port forwarding and thus can act as a server to the other.

Solutions:

A workaround to connect two clients which are locked behind non-forwarding NATs would be to add the ability to use a 3rd client which is server-capable as a middle-man between them.

When two clients are behind the same NAT, they could exchange their LAN IPs via the central server and use these to connect to each other.

If you try to make this working over the internet, you should look at STUN . I don't know if there are any libraries available that are "ready-to-use", but this article should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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