聊天窗口2

2016-11-28  本文已影响0人  Icatream

服务端

package talkingthread;

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

public class ChatServer2 {
    private static ArrayList<PrintWriter> chatmes = new ArrayList<PrintWriter>();
    public static class MyThread implements Runnable{
        Socket socket;
        BufferedReader reader;
        public MyThread(Socket nSocket) {
            socket = nSocket;
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            String message = "";
            try {
                while ((message = reader.readLine()) != null) {
                    chatmes.add(new PrintWriter(socket.getOutputStream()));
                    sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static void sendMessage(String message) {
            Iterator<PrintWriter> iterator = chatmes.iterator();
            while (iterator.hasNext()) {
                PrintWriter writer = iterator.next();
                writer.println(message);
                writer.flush();
            }
        }
        public static void main(String[] args) throws IOException {
            @SuppressWarnings("resource")
            ServerSocket server = new ServerSocket(10000);
            while (true) {
                Socket socket = server.accept();
                MyThread thread = new MyThread(socket);
                thread.run();
            }
        }
    }
}

客户端

package talkingthread;

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

public class ChatClient2 {
    public static void main(String[] args) throws Exception,IOException{
        @SuppressWarnings("resource")
        Socket socket = new Socket("localhost", 10000);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = reader.readLine();
            out.println(msg);
            out.flush();
            System.out.println(in.readLine());
        }
    }
}

debug了一下,服务端的java ArrayList<PrintWriter> chatmes出了点问题,为什么OutputStream里的内容添加不进去?
ArrayList 写的不对,已更改
java private static ArrayList<PrintWriter> chatmes = new ArrayList<PrintWriter>();
返还的内容有些问题

上一篇下一篇

猜你喜欢

热点阅读