[英]OutputStream not working after InputStream
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.我对 sockets 和 J2ME 很陌生,我想创建一个应用程序,它将一些文本发送到服务器(通过套接字)然后接收答案。 So when I try to write the output, I get an exception:
因此,当我尝试编写 output 时,出现异常:
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):这是我的服务器代码(run() 方法):
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:这是 J2ME 客户端代码:
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()
:这里的问题是您关闭了
Socket.getInputStream()
返回的InputStream
:
InputStream in = socket.getInputStream();
String str = readAll(in);
in.close();
From the Javadoc of Socket.getInputStream()
:来自
Socket.getInputStream()
的Javadoc :
Closing the returned InputStream will close the associated socket.
关闭返回的 InputStream 将关闭关联的套接字。
So after executing the code above, your socket will be closed.所以在执行了上面的代码之后,你的socket就会被关闭。
tl;dr : Don't close the InputStream if you still need the OutputStream. tl;dr :如果您仍然需要 OutputStream,请不要关闭 InputStream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.