Tuesday, December 17, 2013

Java exercise - Client and Server example II, ServerSocket stay in loop

In the previous exercise of "client and server to communicate using Socket", the host.java stay waiting request from client.java, and terminate after responsed. In this step, it's modified to stay in loop, for next request; until user press Ctrl+C to terminate the program.

host stey in loop
host stey in loop, until Ctrl+C.

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());
            
            System.out.println(
                "This program will stay monitoring port 80.");
            System.out.println(
                "Until user press Ctrl+C to terminate.");
            
            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = 
                        new PrintStream(outputStream)) {
                            printStream.print(
                                "Hello from Raspberry Pi, you are #" 
                                + count);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}

Keep using the client.java in last exercise of "client and server to communicate using Socket".



Next exercise: - Client and Server example III, run socket operation in background thread.

No comments: