I use the code below to send data to a tcp server. I assume that I need to use socket.shutdownOutput() to correctly indicate that the client sent the request. Is my assumption correct? If not, tell me the purpose of shutdownOutput() . Also appreciate any further optimizations I can do.
Client
def address = new InetSocketAddress(tcpIpAddress, tcpPort as Integer) clientSocket = new Socket() clientSocket.connect(address, FIVE_SECONDS) clientSocket.setSoTimeout(FIVE_SECONDS) // default to 4K when writing to the server BufferedOutputStream outputStream = new BufferedOutputStream(clientSocket.getOutputStream(), 4096) //encode the data final byte[] bytes = reqFFF.getBytes("8859_1") outputStream.write(bytes,0,bytes.length) outputStream.flush() clientSocket.shutdownOutput()
Server
ServerSocket welcomeSocket = new ServerSocket(6789) while(true) { println "ready to accept connections" Socket connectionSocket = welcomeSocket.accept() println "accepted client req" BufferedInputStream inFromClient = new BufferedInputStream(connectionSocket.getInputStream()) BufferedOutputStream outToClient = new BufferedOutputStream(connectionSocket.getOutputStream()) ByteArrayOutputStream bos=new ByteArrayOutputStream() println "reading data byte by byte" byte b=inFromClient.read() while(b!=-1) { bos.write(b) b=inFromClient.read() } String s=bos.toString() println("Received request: [" + s +"]") def resp = "InvalidInput" if(s=="hit") { resp = "some data" } println "Sending resp: ["+resp+"]" outToClient.write(resp.getBytes()); outToClient.flush() }
source share