Android socket客户端从服务器获得回复

时间:2015-11-16 12:56:52

标签: android sockets

我是socket的新手。我真的需要你的帮助。 我在android中创建了一个socket客户端,并成功地向服务器发送了一张图片。我想做的下一个任务是从服务器接收JSON文件作为回复。然而,在关闭了游戏后,它总是告诉我,"套接字已关闭"。

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
InputStream inputStream = socket.getInputStream();
//!!it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
    System.out.println(new String(buffer, 0, temp));
}

我尝试了很多方法来解决它。 1.最近关闭了出口

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
InputStream inputStream = socket.getInputStream();
byte buffer[] = new byte[1024 * 4];
int temp = 0;
//!!My client seems to wait for some messages from server.
//However, since I didn't close the outputStream, the server can't stop writing the file from my outputStream.
//As a result, the server can't send back JSON file to me as a reply.
//My server and client all go blocked.
while ((temp = inputStream.read(buffer)) != -1) {
    System.out.println(new String(buffer, 0, temp));
}
out.close();

2.再次连接插座

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
socket.connect(sc_add,2000);
//!!it will tell me the socket is already connected this time
InputStream inputStream = socket.getInputStream();
//it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
    System.out.println(new String(buffer, 0, temp));
}

感谢您的帮助。

0 个答案:

没有答案