集册 Java实例教程 使用线程响应套接字服务器中的每个客户端请求

使用线程响应套接字服务器中的每个客户端请求

欢马劈雪     最近更新时间:2020-01-02 10:19:05

341
使用线程响应套接字服务器中的每个客户端请求

import java.io.PrintWriter;
/**
来 自 时代Java - N o w  J a v a . c o m
**/

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 {

      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));//时代Java公众号 - N o w J a  v a . c o m 提 供

        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);

  }

}


展开阅读全文