简体   繁体   中英

Why a “java.net.SocketException: Broken pipe” will occur?

I wrote a simple socket programme, it works fine, but my friend use a port scanning tool, when it scan to the port I am using, it cash with "java.net.SocketException: Broken pipe" error, what's happen? and how to solve it?

providerSocket = new ServerSocket(portNum);
connection = providerSocket.accept();
if (connection.getOutputStream() != null) {
    //this line crash!!!
    out = new ObjectOutputStream(connection.getOutputStream());
    out.flush();

}

Detail Error from console:

java.net.SocketException: Broken pipe
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756)
    at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:230)

Some port scanners work by starting to open a connection and then immediately terminating it. Your server is not programmed to deal with a connection failure because you did not code for that possibility. You will need to use a try/catch to trap that condition and recover. Also, you should probably be handing off the connection to a separate thread for processing, so your main program can continue to receive new connections (and sending them to threads to be handled).

我认为当远程端关闭连接时会发生这种情况;

The reason of your problem may be here:

JavaDoc:

The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.

And you should increase "backlog" parameter of your ServerSocket, for example

int backlogSize = 50 ;
providerSocket = new ServerSocket(portNum, backlogSize);

要么使用带有SocketException和IOException的throws子句,要么最后按照我朋友的建议放入try catch。最后不要忘记关闭你正在使用的所有流。并检查你的端口号在客户端和服务器端程序.Hopw这将有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM