Create socket server with ServerSocket and send string message - Java Network

Java examples for Network:ServerSocket

Description

Create socket server with ServerSocket and send string message

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 {//w w  w. ja  va  2  s.c  o  m
      System.out.println("Listening on port " + port);
      ServerSocket ss = new ServerSocket(port);

      Socket s = ss.accept();

      String client;
      client = s.getInetAddress().toString();
      System.out.println("Connected to " + client);

      Scanner in;
      in = new Scanner(s.getInputStream());
      PrintWriter out;
      out = new PrintWriter(s.getOutputStream(), true);

      out.println("Welcome to BartServer 1.0");
      out.println("Enter GET to get a quote " + "or 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();
      System.out.println("Closed connection to " + client);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

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