Как исправить проблемы соединения между клиентом и сервером? - PullRequest
0 голосов
/ 30 марта 2020

Я пытаюсь создать простое приложение для чата между клиентом и сервером. Если после ввода некоторого текста в текстовое поле «отправка» нажать клавишу ввода, он будет получен в текстовом поле «получение» клиента и сервера соответственно. Проблема, которую я получаю, - это установление соединения между клиентом и сервером.

Клиент:

public class SOB48 extends Application {
    static ServerSocket ss;
    static Socket s;
    static DataInputStream dis;
    static DataOutputStream dos;

    @Override
    public void start(Stage primaryStage) {
        Label lblClient= new Label();
        lblClient.setText("Client");

        Label lblServer = new Label();
        lblServer.setText("Server");
        TextArea ta = new TextArea();
        ta.setEditable(false);
        TextArea ta2 = new TextArea();
        ScrollPane Top = new ScrollPane();

        Top.setPannable(true);
       Top.setPrefSize(400,200);
        Top.setContent(ta);
        ScrollPane Bottom = new ScrollPane();

        Bottom.setPannable(true);
        Bottom.setContent(ta2);
        Bottom.setPrefSize(400,200);
        Button btn = new Button();
        btn.setText("Say 'Hello World'");



        ta2.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
              if(event.getCode() == KeyCode.ENTER)
              {
                  try{

                     String msgIn="";
                     s=new Socket("localhost",8000);
                     dis= new DataInputStream(s.getInputStream());
                     dos= new DataOutputStream(s.getOutputStream());

                     while(!msgIn.equals("exit")) {
                         msgIn= dis.readUTF();
                         ta.setText(ta.getText()+"\n Server: " + msgIn);
                     }

                      String msgOut="";
                      msgOut= ta2.getText();
                      dos.writeUTF(msgOut);
                      ta2.setText("");




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

        GridPane gp = new GridPane();
        gp.getChildren().addAll(Top,Bottom,ta,ta2,lblClient,lblServer);
        GridPane.setConstraints(lblServer, 7, 0);
        GridPane.setConstraints(lblClient, 7,30);
        GridPane.setConstraints(Top,150,2,10,2);
        GridPane.setConstraints(Bottom,150,50,10,2);






        Scene scene = new Scene(gp, 250, 500);

        primaryStage.setTitle("SOB 48 Client");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

Сервер:

public class SOB48_Server extends Application {

    static ServerSocket ss;
    static Socket s;
    static DataInputStream dis;
    static DataOutputStream dos;

    @Override
    public void start(Stage primaryStage) {
       Label lblClient= new Label();
        lblClient.setText("Client");

        Label lblServer = new Label();
        lblServer.setText("Server");
        TextArea ta = new TextArea();
        ta.setEditable(false);
        TextArea ta2 = new TextArea();
        ScrollPane Top = new ScrollPane();

        Top.setPannable(true);
        Top.setPrefSize(400,200);
        Top.setContent(ta);
        ScrollPane Bottom = new ScrollPane();

        Bottom.setPannable(true);
        Bottom.setContent(ta2);
        Bottom.setPrefSize(400,200);



         ta2.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
              if(event.getCode() == KeyCode.ENTER)
              {
                  try{

                     String msgIn="";
                     ss= new ServerSocket(8000);
                     s=ss.accept();
                     dis= new DataInputStream(s.getInputStream());
                     dos= new DataOutputStream(s.getOutputStream());

                     while(!msgIn.equals("exit")) {
                         msgIn= dis.readUTF();
                         ta.setText(ta.getText()+"\n Client: " + msgIn);
                     }

                      String msgOut="";
                      msgOut=ta2.getText();
                      dos.writeUTF(msgOut);
                      ta2.setText("");




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

        GridPane gp = new GridPane();
        gp.getChildren().addAll(Top,Bottom,ta,ta2,lblClient,lblServer);
        GridPane.setConstraints(lblClient, 7, 0);
        GridPane.setConstraints(lblServer, 7,30);
        GridPane.setConstraints(Top,150,2,10,2);
        GridPane.setConstraints(Bottom,150,50,10,2);

        Scene scene = new Scene(gp, 300, 250);

        primaryStage.setTitle("SOB 48 Server");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

Ошибка:

Mar 30, 2020 6:15:03 PM sob48.SOB48$1 handle
SEVERE: null
java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:606)
    at java.net.Socket.connect(Socket.java:555)
    at java.net.Socket.<init>(Socket.java:451)
    at java.net.Socket.<init>(Socket.java:228)
    at sob48.SOB48$1.handle(SOB48.java:76)
    at sob48.SOB48$1.handle(SOB48.java:67)
    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.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$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
    at java.lang.Thread.run(Thread.java:748)
...