socket.shutdownOutput()的目的
我正在使用下面的代码将数据发送到TCP服务器。我假设我需要使用socket.shutdownOutput()
正确地指示客户端已完成发送请求。我的假设正确吗?如果不行,请让我知道目的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()
}
回答:
Socket.shutdownOutput()
表示客户端已完成通过TCP连接的所有数据发送。它将发送剩余的数据,然后发送终止序列,该序列将完全关闭其OUTGOING连接。无法发送任何进一步的数据,这也将向您的程序表明请求已完全完成。因此,如果您确定不必再发送任何数据,则建议这样做。
但是不需要指示请求已完成(如果有多个请求,您不必一直打开/关闭输出),还有其他方法。
以上是 socket.shutdownOutput()的目的 的全部内容, 来源链接: utcz.com/qa/431713.html