Use thread to react each client request in a socket server - Java Network

Java examples for Network:ServerSocket

Description

Use thread to react each client request in a socket server

Demo Code

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int port = 1234;

    Message bart = new Message();

    try {//from ww w .  j av  a2s .c om
      System.out.println("Listening on port " + port);
      ServerSocket ss = new ServerSocket(port);

      while (true) {
        Socket s = ss.accept();
        System.out.println("Connection established!");
        Thread t = new Thread(new BartThread(s, bart));
        t.start();
      }
    } catch (Exception e) {
      System.out.println("System exception!");
    }
  }
}

class BartThread implements Runnable {
  private Socket s;
  private Message bart;

  public BartThread(Socket socket, Message bart) {
    this.s = socket;
    this.bart = bart;
  }

  public void run() {
    String client = s.getInetAddress().toString();
    System.out.println("Connected to " + client);
    try {
      Scanner in = new Scanner(s.getInputStream());
      PrintWriter out;
      out = new PrintWriter(s.getOutputStream(), true);

      out.println("Welcome to the Bart Server");
      out.println("Enter BYE to exit.");

      while (true) {
        String input = in.nextLine();
        if (input.equalsIgnoreCase("bye"))
          break;
        else if (input.equalsIgnoreCase("get")) {
          out.println(bart.getQuote());
          System.out.println("Serving " + client);
        } else
          out.println("Huh?");
      }
      out.println("So long, suckers!");
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("Closed connection to " + client);
  }
}

class Message {
  ArrayList<String> q = new ArrayList<String>();

  public Message() {
    q.add("A");
    q.add("B");
    q.add("C");
    q.add("D");
  }

  public String getQuote() {
    int i = (int) (Math.random() * q.size());
    return q.get(i);
  }
}

Related Tutorials