gpt4 book ai didi

java - SwingWorker 并从套接字检索数据

转载 作者:行者123 更新时间:2023-12-02 08:00:06 26 4
gpt4 key购买 nike

我有这样的代码

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");
}
}

}

现在我无法从服务器向客户端发送消息,但来自客户端的消息不会显示在文本区域中。我从早上就开始战斗,我不知道 Swingworker 是如何工作的......

PS。前面的 try ... catch 位于按钮操作执行函数中(如果有任何区别)

最佳答案

您从未在 SwingWorker 上调用 execute,这是您的第一个错误。从那里开始..

关于java - SwingWorker 并从套接字检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com