服務(wù)端
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了一下格带,服務(wù)端的java ArrayList<PrintWriter> chatmes
出了點(diǎn)問題膜蛔,為什么OutputStream里的內(nèi)容添加不進(jìn)去?
ArrayList 寫的不對(duì),已更改
java private static ArrayList<PrintWriter> chatmes = new ArrayList<PrintWriter>();
返還的內(nèi)容有些問題