我有这样的代码
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(888);
} catch (IOException e) {}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
outputLine = "SRV:>"+inputLine+"<:VRS";
out.println(outputLine);
taWyjscie.append(outputLine+"\n");
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException ex) {
taWyjscie.append("Błąd I/O: "+ex.getLocalizedMessage() + "\n");
}
它可以工作,但是在客户端发送“再见”之前,应用程序无法使用。
我希望能够通过gui从服务器向客户端发送消息,所以我与SwingWorker打架,我得到了这个:
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(888);
} catch (IOException e) {}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
zadanie = new ServerTask(in);
} catch (IOException ex) {
taWyjscie.append("Błąd I/O: "+ex.getLocalizedMessage() + "\n");
}
private class ServerTask extends SwingWorker<String, String> {
private BufferedReader iin;
public ServerTask(BufferedReader win) {
this.iin = win;
}
@Override
protected String doInBackground() throws Exception {
String input;
while ((input = iin.readLine()) != null) {
System.out.println(input);
publish(input);
if (isCancelled())
break;
}
return null;
}
@Override
protected void process(List<String> chunks) {
for(String el : chunks) {
textAreaOUT.append(el+"\n");
}
}
}
现在我无法从服务器向客户端发送消息,但是来自客户端的消息不会显示在textArea中。我从早上起就打架了,我不知道swingworker是如何工作的......
PS。这个尝试...前面的catch是按钮动作执行功能(如果它有任何差异)
答案 0 :(得分:2)
您永远不会在execute
上致电SwingWorker
,这是您的第一个错误。从那里开始......