java网络编程-简单聊天室的实现

服务端

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

public class Server {
    private ServerSocket socket;
    private Integer port;
    private List<Socket> socketList;
    private ArrayBlockingQueue<String> queue;

    public Server(Integer port) throws IOException {
        this.port = port;
        socket = new ServerSocket(port);
        /**
         * 这里要用线程安全的类,因为可能有2个线程在操作该数据结构
         */
        socketList = Collections.synchronizedList(new ArrayList<>());
        /**
         * 阻塞队列,队列为空就阻塞当前线程
         */
        queue = new ArrayBlockingQueue<>(100);
    }

    private void openNewServerThread(Socket st){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(st.getInputStream()));
                    while (!socket.isClosed()){
                        String s = br.readLine();
                        if (s.equalsIgnoreCase("quit")){
                            socket.close();
                            break;
                        }
                        queue.add(s);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void run() throws InterruptedException, IOException {
        //接收新客户端
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Socket accept = socket.accept();
                        System.out.println("新连接");
                        socketList.add(accept);
                        openNewServerThread(accept);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        while (true){
            String s = queue.take();

            System.out.println("服务器接受到信息:" + s);
            //通知所有客户端,有消息更新
            for (Socket ts : socketList) {
                if (ts.isClosed()){
                    socketList.remove(ts);
                    continue;
                }
                try {
                    PrintStream ps = new PrintStream(ts.getOutputStream());
                    ps.println(s);
                    ps.flush();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        new Server(8969).run();
    }
}

客户端

package test;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {

    private Socket socket;
    private String ip;
    private Integer port;
    private String clientName;
    PrintStream ps;
    BufferedReader br;

    public Client(String clientName, String ip, Integer port) throws IOException {
        this.ip = ip;
        this.port = port;
        this.clientName = clientName;
        socket = new Socket(ip, port);
        ps = new PrintStream(socket.getOutputStream());
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void sendMsg(String msg) {
        ps.println(clientName + ":" + msg);
        ps.flush();
    }

    /**
     * 收到服务端消息
     */
    public void onReceive(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!socket.isClosed()) {
                        String s = br.readLine();
                        System.out.println("onReceive:" + s);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void close() throws IOException {
        br.close();
        ps.close();
        socket.close();
    }

    public void run() throws IOException {
        onReceive();
        Scanner sc = new Scanner(System.in);
        while (true){
            String s = sc.nextLine();
            sendMsg(s);
            if ("quit".equalsIgnoreCase(s)){
                break;
            }
        }
        close();
    }

    public static void main(String[] args) throws IOException {
        new Client("user1", "127.0.0.1", 8969).run();
    }
}


你可能感兴趣的:(java,网络,开发语言)