I have code like this
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");
}
It works, but app is unusable until client sends “Bye.”.
I want to be able to send messages to client from server by gui, so im fighting with SwingWorker, i got this:
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");
}
}
}
now i cant send message from server to client, but messages from client are not displayed in textArea. Im fighting with since morning and i cant get idea how swingworker is working…
PS. this try … catch in front is in button actionperformed function (if it makes any differece)
You never call
executeon yourSwingWorker, thats your first bug. Start there..