Search code examples
javanetwork-programmingioinputstreambufferedreader

Java networking IO server setup


I want to play around with the Java networking I/O streams and API. I have a laptop and a PC on my network (I know the IP's to each of these devices) that connects through a Netgear DG834 router.

How would I configure my laptop as the "server" and my PC as the "client" when toying with java networking I/O streams.

Thanks!


Solution

  • You are looking for simple TCP communication using sockets. Take a look at this tutorial, it has it all for you to start: http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

    Basic idea is to have a server that listens at a certain port:

    String clientSentence;          
    String capitalizedSentence;          
    
    //server listes at port number
    ServerSocket welcomeSocket = new ServerSocket(6789);          
    
    //server is running forever...
    while(true) {
        //... and is accepting connections
        Socket connectionSocket = welcomeSocket.accept();
    
        //receives string messages ...
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));             
    
        //... and sends messages
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());             
        clientSentence = inFromClient.readLine();             
        System.out.println("Received: " + clientSentence);             
        capitalizedSentence = clientSentence.toUpperCase() + '\n';              
        outToClient.writeBytes(capitalizedSentence);          
    }
    

    And the client should look like this:

    String sentence= "this is a message";   
    String modifiedSentence;   
    
    //client opens a socket
    Socket clientSocket = new Socket("localhost", 6789);   
    
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());   
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));   
    
    //writes to the server
    outToServer.writeBytes(sentence + '\n');   
    modifiedSentence = inFromServer.readLine();   
    
    System.out.println("FROM SERVER: " + modifiedSentence);   
    
    //communication is finished, close the connection
    clientSocket.close();