集册 Java实例教程 使用server socket创建socket服务器并发送字符串消息

使用server socket创建socket服务器并发送字符串消息

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

396
使用server socket创建socket服务器并发送字符串消息

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


      Socket s = ss.accept();


      String client;

      client = s.getInetAddress().toString();

      System.out.println("Connected to " + client);/* from n o w j a   v  a . c o m - 时  代  Java*/


      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>();
展开阅读全文