I'm quite new to sockets and to J2ME and I want to create an app, that would send some text to a server (via socket) and then receive answer. So when I try to write the output, I get an exception:
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at server.run(server.java:55)
at java.lang.Thread.run(Thread.java:748)
Here is my server code (the run() method):
public void run() {
try {
serverSocket = new ServerSocket(7997);
while (true) {
try {
Socket socket = serverSocket.accept();
System.out.println("connected");
InputStream in = socket.getInputStream();
String str = readAll(in);
in.close();
System.out.println(str);
JSONParser parser = new JSONParser();
JSONObject json = null;
json = (JSONObject) parser.parse(str);
text = (String) json.get("text");
presalt = (String) json.get("salt");
keytoCipher = (String) json.get("key2");
String presdvig = (String) json.get("key1");
sdvig = Long.parseLong(presdvig);
//some methods that work with input
caesarEncode();
ConKey();
precipher();
base64code();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(ciphered.getBytes());
outputStream.flush();
outputStream.close();
} catch (ParseException | IOException e) {
e.printStackTrace();
}
}
//serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And this is the J2ME client code:
try {
System.out.println("connected");
JSONObject json = new JSONObject();
json.put("text", textField.getString());
json.put("salt", "defaultsalt");
json.put("key1", "228");
json.put("key2", "1488");
OutputStream out = sc.openOutputStream();
out.write(json.toString().getBytes());
out.flush();
out.close();
InputStream in = sc.openInputStream();
String str = readAll(in);
System.out.println(str);
fieldzwei.setString(str);
} catch (IOException ex) {
ex.printStackTrace();
} catch (JSONException ex) {
ex.printStackTrace();
}
Also, if I do not send anything to a server and simply send a message from it when it's connected, it works fine. Any ideas where I could be wrong?
The problem here is that you close the InputStream
returned by Socket.getInputStream()
:
InputStream in = socket.getInputStream();
String str = readAll(in);
in.close();
From the Javadoc of Socket.getInputStream()
:
Closing the returned InputStream will close the associated socket.
So after executing the code above, your socket will be closed.
tl;dr: Don't close the InputStream if you still need the OutputStream.