我实现的过程描述一下,有A.B两个客户端分别挂在NA,NB两个nat下面,通过固定IP的服务器S,交换A,B客户端外的nat的公网IP和端口,然后由B向A发起连接,进行打洞(这次绝大多数应该是失败的,我也确实失败了,超时),然后由A再连接B,理论上B已经打过通往A的洞了,这次连接应该能够通过NB跟B连接上,但是我这边失败了,一直连接不上。(以上A,B跟S通讯交换IP已经A,B互相连接和建立监听我都用的同一个端口)。网上有说java的API不支持tcp包组装,所以无法打洞的,我很疑惑,希望做过类似的大家一起过来讨论一下
手机不方便 大致说下b收到服务器返回的a的公网ip和端口 b调用connect方法 大致是这样
final int LOCAL_PORT = 8880; SocketAddress localAddr = new InetSocketAddress(LOCAL_PORT); ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(localAddr); Socket socket = new Socket(); socket.setReuseAddress(true); socket.bind(localAddr); final String SERVER_IP = ""; final int SERVER_PORT = 60000; SocketAddress serverAddr = new InetSocketAddress(SERVER_IP,SERVER_PORT); socket.connect(serverAddr); sendAndRegist(socket); List<InetSocketAddress> addresses = receiveAndGetAddresses(socket); createThreadToDoSomeThing(socket,addresses); while(true){ Socket s = ss.accept(); createThreadToAccept(s); }
public static void serverDemo() throws IOException{ final String SERVER_IP = ""; final int SERVER_PORT = 60000; SocketAddress localAddr = new InetSocketAddress(SERVER_IP,SERVER_PORT); ServerSocket ss = new ServerSocket(); ss.bind(localAddr); while(true){ Socket s = ss.accept(); createThreadToAccept(s); } } private static void createThreadToAccept(Socket s) { ClientInfo info = readRegistInfo(s); info.setSocketAdress(s.getRemoteSocketAddress()); doRegist(info); List<SocketAddress> online = findOnlineAddresses(); writeOnlineAddresses(online); }