如何修复 java 中的 "java.net.SocketException" 错误

How to fix "java.net.SocketException" error in java

关闭客户端 window 时出错,打开新客户端 window 时服务器终端出现错误。我的英语很生疏:P

关闭客户端时出现服务器错误

java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:210)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at main.java.Manager.run(Manager.java:45)

重新打开获取对象时出现客户端错误

java.io.StreamCorruptedException: invalid stream header: 73720013
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
    at java.io.ObjectInputStream.(ObjectInputStream.java:358)
    at main.java.controllers.VendedoresUI.load(VendedoresUI.java:69)
    at main.java.controllers.VendedoresUI.initialize(VendedoresUI.java:54)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at main.java.controllers.Controller.loadUI(Controller.java:150)
    at main.java.controllers.Controller.changeUI(Controller.java:111)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access00(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access00(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent3(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null7(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)

1.Server classes

1.1。 Server.java public class 服务器扩展线程{

    public Server(){}

    public void run() {

        try{

            ServerSocket listener = new ServerSocket(4444);
            listener.setSoTimeout(0);

            System.out.println("Server is now running");

            try {
                while (true) {

                    Socket socket = listener.accept();

                    new Manager(socket).start();
                }
            } finally {
                listener.close();
            }

        } catch (IOException ioexception){

            System.out.println("\u001B[31mError opening server, more info: ");
            System.out.println(ioexception);
            System.out.println("Closing server...");
            System.exit(0);

        }

    }

}

1.2。 Manager.java

public class Manager extends Thread{
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public Manager(Socket socket){
        this.socket = socket;
        System.out.println("\u001B[32m" + socket.getLocalAddress() + ":" + socket.getPort() + " connected");
    }

    @Override
    public void run() {

        try {

            out = new PrintWriter(socket.getOutputStream(), true);

            out.println("Connected");

            while(true) {
                ObjectOutputStream objectOutput = new ObjectOutputStream(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));



                if(in.readLine().contains(Protocols.VENDEDOR_GET_ALL)) {
                    ResultSet res = SQLManager.Query("SELECT * FROM vendedores");
                    List list = new ArrayList();

                    while (res.next()) {
                        Vendedor vendedor = new Vendedor();
                        vendedor.setNOME(res.getString("NOME"));
                        vendedor.setCPF(res.getString("CPF"));
                        vendedor.setCONTATO(res.getString("CONTATO"));
                        vendedor.setCONTA(res.getInt("CONTA"));
                        vendedor.setBANCO(res.getInt("BANCO"));
                        vendedor.setAGENCIA(res.getString("AGENCIA"));
                        vendedor.setCORRENTE(res.getString("CORRENTE"));
                        list.add(vendedor);
                    }
                    objectOutput.writeObject(list);
                }
                objectOutput.flush();
            }

        } catch (IOException e) {
            System.out.println("\u001B[31m" + socket.getLocalAddress() + ":" + socket.getPort() + " disconnected");
            e.printStackTrace();
            interrupt();
        } catch (SQLException | ClassNotFoundException e) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, e);
        }

    }
}

2.Client classes

2.1。 ClientSocket.java

public class ClientSocket {

    private static Socket socket = null;
    private static BufferedReader in;
    private static PrintWriter out;

    public static void load(){
        try {

            socket = new Socket("127.0.0.1", 4444);
            in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            System.out.print(ClientSocket.getIn().readLine());

        } catch(IOException ioexception){
            Logger.getLogger(ClientSocket.class.getName()).log(Level.SEVERE, null, ioexception);
        }
    }

    public static Socket getSocket() {
        return socket;
    }

    public static BufferedReader getIn() {
        return in;
    }

    public static PrintWriter getOut() {
        return out;
    }
}

2.2 VendedoresUI.java

public class VendedoresUI implements Initializable {

    @FXML
    private TableView table;

    @FXML
    private TableColumn colName;

    @FXML
    private TableColumn colCPF;

    @FXML
    private TableColumn colContato;

    @FXML
    private TableColumn colConta;

    @FXML
    private TableColumn colBanco;

    @FXML
    private TableColumn colAgencia;

    @FXML
    private TableColumn colCorrente;

    ObservableList list;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        load();

    }

    private void load(){
        try {
            if(ClientSocket.getSocket().isClosed()){
                ClientSocket.load();
            }

            PrintWriter escritor = new PrintWriter(ClientSocket.getSocket().getOutputStream(), true);

            escritor.println(Protocols.VENDEDOR_GET_ALL);


            ObjectInputStream obi = new ObjectInputStream(ClientSocket.getSocket().getInputStream());
            List mList = (List) obi.readObject();

            list = FXCollections.observableArrayList(mList);

            colName.setCellValueFactory(new PropertyValueFactory("NOME"));
            colCPF.setCellValueFactory(new PropertyValueFactory("CPF"));
            colContato.setCellValueFactory(new PropertyValueFactory("CONTATO"));
            colConta.setCellValueFactory(new PropertyValueFactory("CONTA"));
            colBanco.setCellValueFactory(new PropertyValueFactory("BANCO"));
            colAgencia.setCellValueFactory(new PropertyValueFactory("AGENCIA"));
            colCorrente.setCellValueFactory(new PropertyValueFactory("CORRENTE"));
            table.setItems(list);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

第一个问题:服务器关闭客户端出错,关闭客户端前通知服务器,让服务器停止处理。您可能可以忽略此异常,但最好能有序地关闭连接。

关于第二个问题,客户端在重新打开时出错(java.io.StreamCorruptedException:无效流header): 调试后发现问题所在。下面的代码显示了问题所在。

复制粘贴并运行 as Junit 以查看它。

import org.junit.Test;    
import java.io.*;
import java.net.*;    
import static java.lang.System.*;

public class ServerSocketTest {

    /**
     * Runs first to start server. This is the corrected server
     */
    @Test
    public void startServerTest() throws Exception {
        ServerSocket listener = new ServerSocket(4444);
        while (true) {
            try (Socket socket = listener.accept()) {
                new PrintWriter(socket.getOutputStream(), true).println("Connected");
                new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();//read "ALL" from client
                new ObjectOutputStream(socket.getOutputStream()).writeObject("String Object");
            }
        }
    }

    /**
     * Run client Twice to see error
     */
    @Test
    public void startClientTest() throws Exception {
        Socket s = new Socket("127.0.0.1", 4444);
        out.println(new BufferedReader(new InputStreamReader(s.getInputStream())).readLine());
        new PrintWriter(s.getOutputStream(), true).println("ALL");//tell server we want all the data
        out.println(new ObjectInputStream(s.getInputStream()).readObject());
    }

    /**
     * This implementation will error out on second test
     */
    @Test
    public void errorServerTest() throws Exception {
        ServerSocket listener = new ServerSocket(4444);
        while (true) {
            try (Socket socket = listener.accept()) {
                new PrintWriter(socket.getOutputStream(), true).println("Connected");
                /*
                * Issue is here. The sequence of object construction matters.
                * The Constructor has side effects. To correct, move this contructor below InputStreamReader.
                * */
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();//read "ALL" from client
                objectOutputStream.writeObject("String Object");
            }
        }
    }
}

基本上,问题在于 BufferedReader 和 ObjectOutputStream 之间 object 创建的顺序。

要修复您的错误,请最后构造 ObjectOutputStream。