Reputation: 5880
I having the following code to create a client socket to send/receive data:
val socket:Socket = new Socket(InetAddress.getByName("127.0.0.1"), 7777)
val inputStream = socket.getInputStream()
val bufferSource = new BufferedSource(inputStream)
val out = new PrintStream(socket.getOutputStream())
var data = "Hello Everyone"
out.println(data)
out.flush()
***socket.shutdownOutput()***
val in = bufferSource.getLines()
if (in.hasNext) {
println(in.next())
}
If I don't run socket.shutdownOutput(), I won't get the data from server, because Server side is still waiting the input. Therefore I have to shutdown the outputStream. But if shutdown the output, it can not be reopen. So I have to create a new socket for sending new data. That caused sending one record needs to create a new socket. This is really awkward. Is there any other way to tell the server that the output already finished without shutting down the output please. Thanks in advance!
Upvotes: 1
Views: 70
Reputation: 84169
The problem is that the server doesn't know when to stop reading and process and reply.
What you need here is an application-level protocol that would dictate how server and clients are to communicate - what is a command, how a response to be formatted, etc.
This could be a line-oriented protocol - each new line represents a message (in general the message delimiter could be any other character sequence not appearing in the messages). Or it could be fixed length messages; or messages pre-pended with message length (or type) to let the other side know how much data yo expect.
Upvotes: 1