Connect two client sockets

前端 未结 12 1486
执笔经年
执笔经年 2020-12-10 03:58

Let\'s say Java has two kind of sockets:

  • server sockets \"ServerSocket\"
  • client sockets or just \"Socket\"

Imagine the situation of two

12条回答
  •  Happy的楠姐
    2020-12-10 04:23

    I understand what you are after - I have had to solve the same problem in situations where the server was behind a masquerading firewall with a dynamic IP. I used a small freely available program, javaProxy to provide a solution. It makes the server appear as a client socket - internally, it is still a server, but javaProxy provides forwarding program - My App in the example - that creates client connections "from" the server. It also provides the proxy in the middle (Middle Server, in the example) to join the two client ends together - the client socket forwarded from the server, and the client socket from the actual client trying to connect to the server.

    The Middle Server is hosted outside the firewall on a known IP. (Even though we can pretend to do this without server sockets, each connection must involve a client and a server end and so we make sure the Middle Server is on an IP that the clients can reach.) In my case I just used a simple hosting provider that let me run a java from the shell.

    With this setup, I could provide access to remote desktop and other services running behind a NAT firewall with dynamic IP, with access from my home machine which also was behind a NAT with dynamic IP. The only IP address I needed to know was the IP of the Middle Server.

    As to threading, the javaproxy library is almost certainly implemented using threads to pump data between the client sockets, but these do not consume any CPU resources (or power) while they are blocking waiting for I/O. When java 7 is released with support for asynchronous I/O then one thread per client socket pair will not be necessary, but this is more about performance and avoiding limits on the maximum number of threads (stack space) rather than power consumption.

    As to implementing this yourself with two client sockets in the same process requires the use of threads so long as java is dependent upon blocking I/O. The model is pull from the read end and push to the write end, so a thread is needed to pull from the read end. (If we had push from the read end, i.e asynchornous I/O then a dedicated thread per socket pair would not be needed.)

提交回复
热议问题