아래 코드를 사용하여 데이터를 tcp 서버에 보내고 있습니다. 클라이언트가 요청을 완료했음을 적절히 나타내려면 socket.shutdownOutput()
을 사용해야한다고 가정합니다. 내 가정이 맞습니까? 그렇지 않다면 shutdownOutput()
의 목적을 알려주십시오. 또한 내가 할 수있는 추가 최적화에 대해 감사드립니다.socket.shutdownOutput() 목적
클라이언트
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()
서버
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()
}
+1 당신은 그러나 그 요청이 완료되었음을 나타 내기 위해 필요한 (당신은 출력을 닫으/열 필요하지는 없습니다 "에 정교한 모든 여러 요청이있는 경우 시간), 다른 방법이 있습니다. " –
서버에 보낼 요청이 여러 개인 경우 "마법 패키지"(특수한 ** 고유 바이트 배열 **)를 정의 할 수 있으며이를 보내면 하나의 요청이 끝난 서버를 나타냅니다. – Leander
간단한 예제 (더 정교하고 중요한 프로그램에는 적합하지 않음)는 문자열 "End"의 바이트 배열이 될 것이며 문자열을 보내지 않는다고 가정합니다. – Leander