这是一个非常简单的Java客户端/服务器应用程序。在这里,我尝试同步对ArrayList的访问。但是,抛出异常。而且我认为我已经保护了我应该做的一切。任何人都可以帮助解释这段代码的错误吗?还有什么需要注意的吗?
public class ChatServerSynchronized {
public static void main(String[] args) {
new ChatServerSynchronized().go();
}
private ArrayList<ClientHandler> clients;
private int numOfClients;
public ChatServerSynchronized() {
clients = new ArrayList<ClientHandler>();
numOfClients = 0;
}
public void go() {
try {
ServerSocket ss = new ServerSocket(10000);
System.out.println("Listening at 10000");
while(true) {
Socket s = ss.accept();
int thisClient = (++numOfClients);
ClientHandler client = new ClientHandler(thisClient, s);
System.out.println("New connection: "+thisClient);
addClient(client);
new Thread(client).start();
}
} catch (IOException e) {
}
}
public synchronized void addClient(ClientHandler client) {
clients.add(client);
}
public synchronized void removeClient(ClientHandler client) {
clients.remove(client);
}
public synchronized void broadcast(String message) {
for(ClientHandler client: clients) {
client.send(message);
}
}
private class ClientHandler implements Runnable {
private BufferedReader in;
private PrintWriter out;
private int id;
public ClientHandler(int clientID, Socket s) throws IOException {
id = clientID;
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream());
}
public void run() {
try {
while(true) {
String message = in.readLine();
if(message == null)
break;
System.out.println(id+": Message '"+ message + "' received");
broadcast(id+": "+message);
}
} catch (IOException e) {
//System.out.println(e);
//This is where the exception is thrown
} finally {
System.out.println("Closed: "+id);
removeClient(this);
}
}
public void send(String message) {
out.println(message);
out.flush();
}
}
}
答案 0 :(得分:-1)
这可能是因为您关闭了客户端上的连接并将流保存在服务器上。因此,如果您写入已关闭的套接字(由客户端关闭) - &gt;错误。
即使你不写,我会在客户端停止连接/中止时立即出现错误。 (有人应该确认这一点)在你的客户端设置一个Thread.sleep(5000)然后你可能在5秒后看到错误。 :)
Jeerze,
西蒙