当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java java.net.SocketException用法及代码示例


SocketException 是 IOException 的子类,因此它是一个受检查的异常。这是最常见的异常,在尝试打开或访问套接字时表示出现问题。此错误的完整异常层次结构是:

java.lang.Object
     java.lang.Throwable
         java.lang.Exception
             java.io.IOException
                 java.net.SocketException

您可能已经知道,强烈建议使用最具体的套接字异常类,以更准确地指定问题。还值得注意的是,SocketException 通常会附带一条错误消息,该消息对于导致异常的情况提供了非常丰富的信息。

Implemented Interfaces: Serializable
Direct Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException

什么是套接字编程?

它是一种利用套接字建立连接并使多个程序能够使用网络相互交互的编程概念。套接字提供了使用网络协议栈建立通信的接口,并使程序能够通过网络共享消息。套接字是网络通信中的端点。套接字服务器通常是可以接受套接字连接请求的多线程服务器。套接字客户端是发起套接字通信请求的程序/进程。

java.net.SocketException:连接重置

当客户端在通过套接字返回响应之前关闭套接字连接时,此 SocketException 发生在服务器端。例如,在检索响应之前退出浏览器。连接重置仅仅意味着收到了 TCP RST。 TCP RST 数据包是远程端告诉你之前发送的 TCP 数据包的连接无法识别,也许连接已经关闭,也许端口没有打开,诸如此类。重置数据包只是一个没有有效负载且在 TCP 标头标志中设置了 RST 位的数据包。

现在从实现开始,很明显我们需要两个程序,一个处理客户端,另一个处理服务器。它们如下:

示例 1:服务器端

Java


// Java Program to Illustrate SocketException
// Server Side App
// Importing required classes
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
// Main class
public class SimpleServerApp {
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
        new Thread(new SimpleServer()).start();
    }
    static class SimpleServer implements Runnable {
        // run() method for thread
        @Override public void run()
        {
            ServerSocket serverSocket = null;
            // Try block to check for exceptions
            try {
                serverSocket = new ServerSocket(3333);
                serverSocket.setSoTimeout(0);
                // Till condition holds true
                while (true) {
                    try {
                        Socket clientSocket
                            = serverSocket.accept();
                        // Creating an object of
                        // BufferedReader class
                        BufferedReader inputReader
                            = new BufferedReader(
                                new InputStreamReader(
                                    clientSocket
                                        .getInputStream()));
                        System.out.println(
                            "Client said :"
                            + inputReader.readLine());
                    }
                    // Handling the exception
                    catch (SocketTimeoutException e) {
                        // Print the exception along with
                        // line number
                        e.printStackTrace();
                    }
                }
            }
            // Catch block to handle the exceptions
            catch (IOException e1) {
                // Display the line where exception occurs
                e1.printStackTrace();
            }
            finally {
                try {
                    if (serverSocket != null) {
                        serverSocket.close();
                    }
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


示例 2:客户端

Java


// Java Program to Illustrate SocketException
// Client Side App
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
// Class 1
// Main class
public class SimpleClientApp {
    // Main driver method
    public static void main(String[] args)
    {
        // Calling inside main()
        new Thread(new SimpleClient()).start();
    }
    // Class 2
    // Helper class
    static class SimpleClient implements Runnable {
        // run() method for the thread
        @Override public void run()
        {
            // Initially assign null to our socket to be
            // used
            Socket socket = null;
            // Try block to e=check for exceptions
            try {
                socket = new Socket("localhost", 3333);
                // Creating an object of PrintWriter class
                PrintWriter outWriter = new PrintWriter(
                    socket.getOutputStream(), true);
                // Display message
                System.out.println("Wait");
                // making thread to sleep for 1500
                // nanoseconds
                Thread.sleep(15000);
                // Display message
                outWriter.println("Hello Mr. Server!");
            }
            // Catch block to handle the exceptions
            // Catch block 1
            catch (SocketException e) {
                // Display the line number where exception
                // occurred using printStackTrace() method
                e.printStackTrace();
            }
            // Catch block 2
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Catch block 3
            catch (UnknownHostException e) {
                e.printStackTrace();
            }
            // Catch block 4
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    // If socket goes NULL
                    if (socket != null)
                        // Close the socket
                        socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


输出:

java.net.SocketException: Connection reset

at java.net.SocketInputStream.read(SocketInputStream.java:196)

at java.net.SocketInputStream.read(SocketInputStream.java:122)

at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)

at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)

at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)

at java.io.InputStreamReader.read(InputStreamReader.java:184)

at java.io.BufferedReader.fill(BufferedReader.java:154)

at java.io.BufferedReader.readLine(BufferedReader.java:317)

at java.io.BufferedReader.readLine(BufferedReader.java:382)

at com.javacodegeeks.core.lang.NumberFormatExceptionExample.SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36)

at java.lang.Thread.run(Thread.java:744)

现在为了摆脱java.net.SocketException 要获得正确的输出,则可以通过就好像您是客户端并在连接到服务器端应用程序时收到此错误来感知它,然后附加以下更改,如下所示:

  1. 首先,通过在服务器运行的主机端口上执行 telnet 来检查服务器是否正在运行。
  2. 检查服务器是否重新启动
  3. 检查服务器是否故障转移到其他主机
  4. 记录错误
  5. 向服务器团队报告问题

Note: In most cases, you will find that either server is not running or restarted manually or automatically.



相关用法


注:本文由纯净天空筛选整理自praveen13kulkarni大神的英文原创作品 java.net.SocketException in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。