Add a timeout when creating a new Socket

前端 未结 2 695
一个人的身影
一个人的身影 2021-01-17 16:03

I have a local network with DHCP and a few PCs. One of these should be my Server and get automatically connected to all others (clients). My idea was this: First, I create a

相关标签:
2条回答
  • 2021-01-17 16:41

    It's much easier to do this with UDP. The general logic would be:

    1. Identify a well known port for 'discovery'
    2. Any machine that starts up sends out a 'Query Master Server' message
    3. If a response is not received to that message within a time frame you define, then the machine that sent it automatically designates itself as being the server.
    4. Henceforth, any machine that sends out a 'Query Master Server' message will get a response back from the master, with its IP address and a 'communication port'
    5. Connect from the new machine to the server on the communication port and start sending messages.

    You might run into situations where more than one server thinks it is the master in this scenario, and then you would need a conflict resolution process, but the outline should give you a general idea of a process that will work for you.

    0 讨论(0)
  • 2021-01-17 16:46

    I've found a solution for my problem. It was just initializing the Socket not with

    Socket s1 = new Socket("192.168.1." + i, 1254);
    

    but with

    Socket s1 = new Socket();
    s1.setSoTimeout(200);
    s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);
    

    Thanks anyway!

    0 讨论(0)
提交回复
热议问题