0

I am creating a basic little game and I want it to be able to scan over a LAN using Sockets, My current code works, however it's crude and slow.

My current code works as such, it gets the current computers first 2 octaves (e.g 192.168), then it does a dual for loop (0- 255) to scan from 192.168.0.0 to 192.168.255.255, In my opinion this is a very inefficient method of scanning through all of the IP's in a LAN.

This is the code:

new Thread(new Runnable() {
@Override
public void run() { 
            int next = 0;
            try{
            String ipAd = InetAddress.getLocalHost().getHostAddress();
            String ipStart = ipAd.substring(0, NetHandler.nthOccurrence(ipAd, '.', 2)-1);

            Socket s;

            for(int i = 0 ; i < 255; i++){
                for(int j = 0 ; j < 255; j++){
                    s = new Socket();
                    String ip = ipStart + (i + "." + j);
                    tests++;
                    server = ip;    
                    try{
                    s.connect(new InetSocketAddress(ip, 26655), 10);
                    }catch(Exception e){
                        continue;
                    }
                    servers[next++] = ip;
                    componentList.add(new GuiButton(ids++, GuiMultiplayer.this, SpaceGame.WIDTH/2, SpaceGame.HEIGHT/4 - 60 + (50 * ids), ip));
                }
            }
            }catch(Exception e){
            }
        }
    }).start();
}

Is there an easier method to maybe list all of the devices on my LAN network? Or is my crude, slow solution the only way?

A preview of this monstrosity:

enter image description here

4

2 回答 2

8

Discovering running instances of your app on a LAN is commonly done using UDP broadcasts. Have the requesting app send a single request message to the LAN's subnet broadcast IP on a pre-determined port, which will copy the message to that port on every PC connected to that subnet. Your other apps can open a UDP listening socket on that port to receive requests with. When each app receives the request, it will have the IP of the requester and can send a reply directly to it, allowing the requester to discover the repliers. After sending the initial request, the requester can wait for a period of time gathering up any replies it receives, and then use the info as needed.

于 2013-02-24T18:03:59.660 回答
1

My suggestion would be to multi-thread your application so that you initiate multiple connections at once. Check out the Java Concurrency tutorials on how to do this if you haven't done multi-threaded Java applications before.

Edit: You can certainly combine this with other people's suggestions in the comments too. In fact, I would probably use their suggestions before dealing with concurrency.

于 2013-02-24T15:10:33.000 回答