Sunday, August 4, 2013

Java: Simple sample of socket server using InetAddress

public static void main(String[] args) {
        // TODO code application logic here
        String hostIP = "127.0.0.1";
        InetAddress bindAddr; 
        try {
            bindAddr = InetAddress.getByName(hostIP);
            launchServerSocket(4567, 4568, bindAddr );
        } catch (UnknownHostException e) {
            System.out.println("Unknown Host: " + hostIP);
            e.printStackTrace(); 
        }                
    }
 
    public static void launchServerSocket(int portNumber, int backlog, InetAddress bindAddr ){
        try {
            ServerSocket serverSocket = new ServerSocket(portNumber, backlog, bindAddr);
            System.in.read();// prevent console to be closed
        } 
        catch (IOException e) {
            System.out.println("Could not listen on port: " + portNumber);
            e.printStackTrace();            
        }
    }

No comments: