當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。