Java实现简单的聊天室(Socket版)

简单的聊天室:

依次启动Server,Client;在Client下输入任意字符后回车,即可在Server上看到,同时Server的回执也会发送至Client下;

server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

   private static final int PORT = 12306;

   public static void main(String[] args) throws IOException {
       ServerSocket server = new ServerSocket(PORT);
       Socket socket = server.accept(); // keep waiting for a collection
       BufferedReader receiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       PrintWriter replier = new PrintWriter(socket.getOutputStream());
       String msg;
       while ((msg = receiver.readLine()) != null) { // receive
           if (msg.equalsIgnoreCase("bye")) break;
           System.out.println(String.format("client: '%s'", msg));
           replier.println(String.format("copy: %s", msg)); // reply
           replier.flush();
       }
       replier.close();
       receiver.close();
       socket.close();
       server.close();
   }
}

client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

   private static final String HOST = "127.0.0.1";
   private static final int PORT = 12306;

   public static void main(String[] args) throws IOException {
       Socket socket = new Socket(HOST, PORT);
       PrintWriter sender = new PrintWriter(socket.getOutputStream());
       BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
       BufferedReader receiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       String msg;
       while ((msg = input.readLine()) != null) {
           if (msg.equalsIgnoreCase("bye")) break;
           sender.println(msg); // send
           sender.flush();
           System.out.println(String.format("server: '%s'", receiver.readLine())); // receive
       }
       sender.close();
       receiver.close();
       socket.close();
   }
}

这是Socket版本,后续会补充Netty实现的版本。

你可能感兴趣的:(Java)