我有一个客户端通过套接字连接到服务器并发送一些数据,服务器读取数据并返回响应。
以下是我从服务器发送和接收数据的方法
public static String sendAndReceiveDataToNode(String address, int port, String data) throws ConnectionFailedException {
Socket me = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String responseData = null;
try {
me = new Socket(address, port);
outputStream = new DataOutputStream(me.getOutputStream());
outputStream.write(data.getBytes());
outputStream.flush();
LOGGER.info("Data written from client");
inputStream = new DataInputStream(me.getInputStream());
responseData = convertStreamToString(inputStream); // here i call inputStream.readLine()
return responseData;
} catch (IOException e) {
e.printStackTrace();
}
finally {
closeOutputStream(outputStream);
closeInputStream(inputStream);
closeSocket(me);
}
return null;
}
如果我使用outputStream.flush()
,那么我的服务器阻塞在inputStream.readLine(),而我写的数据永远不会到达服务器。如果我使用me.shutdownOutput()然后数据到达服务器但客户端不阻塞在inputStream.readLine()从服务器接收数据并读取空字符串,虽然我使用outputStream.flush()时客户端阻止readLine。
在服务器中我有以下代码
public void run() {
DataInputStream inputStream = null;
OutputStream outputStream = null;
while (running) {
try {
this.clientConnection = receptionistSocket.accept();
inputStream = new DataInputStream(clientConnection.getInputStream());
String requestData = Util.convertStreamToString(inputStream); //Here i call inputStrea.readLine()
//Do Some time consuming operation
String data = createResponse(requestData) ;
outputStream = new DataOutputStream(clientConnection.getOutputStream());
outputStream.write(data.getBytes());
} catch (IOException e) {
LOGGER.error("Error occurred while accepting client connection");
LOGGER.error(e.getMessage(), e);
}
catch (Exception e) {
LOGGER.error("Error occurred while accepting client connection");
LOGGER.error(e.getMessage(), e);
}
finally {
Util.closeInputStream(inputStream);
Util.closeOutputStream(outputStream);
}
}
}
修改 下面缺少代码
public static String convertStreamToString(InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
throw e;
} finally {
try {
is.close();
} catch (IOException e) {
throw e;
}
}
return sb.toString();
}
我已经完成了很多教程,但没有一个能解决这个问题。
我错在哪里?