当输入用户名并按下连接按钮时:
public connect{...
sock = new Socket("77.70.65.222", 5000);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
Thread IncomingReader = new Thread(new IncomingReader());
IncomingReader.start();
writer.println("``connecto");
//sends message to server, which sends back a message ,which when read by my
//IncomingReader class(implements Runnable) prints online users in "onlineUsersArea"
writer.flush();
String[] a = onlineUsersArea.getText().split("\n");
for(String s:a){if(s.equals(username)) throw new Exception();}
//throws an exception if the selected username exists
writer.println(username + "`has connected.`Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
...}
问题是该方法不会等待IncomingReader
打印在线用户,因此a[]
在方法完成之前不包含任何内容。我该怎么做才能让它等待IncomingReader
然后继续writer.flush();
如果我添加一个IncomingReader.join();
,在我按下连接按钮后,客户端停止响应。
如果我有其他方法可以阻止用户使用已经使用过的用户名,我将非常高兴听到它。提前致谢!