socket.shutdownOutput() 的目的 [英] purpose of socket.shutdownOutput()

查看:23
本文介绍了socket.shutdownOutput() 的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将数据发送到 tcp 服务器.我假设我需要使用 socket.shutdownOutput() 来正确指示客户端已完成发送请求.我的假设正确吗?如果没有,请让我知道 shutdownOutput() 的目的.也感谢我可以进行的任何进一步优化.

I am using the below code to send data to a tcp server. I am assuming that I need to use socket.shutdownOutput() to properly indicate that the client is done sending the request. Is my assumption correct? If not please let me know the purpose of shutdownOutput(). Also appreciate any further optimizations I can make.

客户

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() means that the client is finished sending any data through the TCP connection. It will send the remaining data followed by a termination sequence which will completely close its OUTGOING connection. It is not possible to send any further data, which will also indicate to your program that the request is completely finished. So its recommended if you are sure you don't have to send any more data.

但是不需要表明请求已经完成(如果有多个请求,不必一直打开/关闭输出),还有其他方式.

But it's not needed to indicate that the request is finished (you don't have to open/close the output all the time if you have multiple requests), there are other ways.

这篇关于socket.shutdownOutput() 的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆