从套接字客户端向SocketServer服务器发送消息时出错[JAVA]

时间:2018-06-05 05:33:18

标签: java sockets networking serversocket

服务器代码

package chatserver;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import java.net.*;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;

public class ChatController implements Initializable {

    private ServerSocket server;
    private Socket userMachine;
    private DataOutputStream os;
    private DataInputStream in;

    @FXML
    private TextField message;

    @FXML
    private ListView messageArea;

    @FXML
    private void sendMessage(ActionEvent event) {
        String mMessage = message.getText().trim();
        if (mMessage.isEmpty()) {
            Alert warn = new Alert(AlertType.WARNING, "Enter a message");
            warn.show();
        } else {
            try {
                this.os.writeUTF(mMessage);
                System.out.println("Message sent");
                this.os.flush();
                message.clear();
                if (!userMachine.isConnected()) {
                    System.out.println("Client disconnected");
                }
            } catch (IOException e) {
                Alert error = new Alert(AlertType.ERROR, "Unable to send message. err: " + e.getMessage());
                error.show();
                e.printStackTrace();
            }
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            server = new ServerSocket(ChatServer.port);
            Alert waiting = new Alert(AlertType.INFORMATION, "Waiting for user at port: " + ChatServer.port +
            " IP: " + server.getInetAddress().toString());
            waiting.show();

            userMachine = server.accept();
            waiting.hide();
            Alert confirm = new Alert(AlertType.CONFIRMATION, "User Connected");
            confirm.show();

            this.os = new DataOutputStream(userMachine.getOutputStream());
            this.in = new DataInputStream(userMachine.getInputStream());

            // start receive thread
            Thread clientThread = new Receive(this.in);
            clientThread.start();
        } catch (IOException e) {
            Alert alert = new Alert(AlertType.ERROR, "Error: " + e.getMessage() + " at line 77");
            alert.show();
        }
    }    

    public class Receive extends Thread {
        DataInputStream in;
        public String mData;

        public Receive(DataInputStream in) {
            this.in = in;
        }

        @Override
        public void run() {
            try {
                int count = 0;

                while (true) {
                    if (in.available() > 0) {
                        try {
                            setData(in.readUTF());
                            Platform.runLater(new Runnable() {
                                @Override 
                                public void run() {
                                    try{
                                      messageArea.getItems().add(getData());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        } catch (EOFException e) {if (count < 1)         {e.printStackTrace(); count ++;}}
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                Platform.runLater(() -> {
                    Alert wentWrong = new Alert(AlertType.ERROR, "SERVER - Error at line 119: Something went wrong while establishing connection: err: " + e.getStackTrace().toString());
                    wentWrong.show();
                });

            }  

        }
        private void setData(String data) {
            this.mData = data;
        }
        private String getData() {
            return this.mData;
        }
    }
}

客户端代码

package chatclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import java.net.*;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;

public class ChatController implements Initializable {

    private Socket client;
    private DataOutputStream os;
    private DataInputStream in;

    @FXML
    private TextField message;

    @FXML
    private ListView messageArea;

    @FXML
    private void sendMessage(ActionEvent event) {
        String mMessage = message.getText().trim();

        if (mMessage.isEmpty()) {
            Alert warn = new Alert(AlertType.WARNING, "Enter a message");
            warn.show();
        } else {
            try {
                os.writeUTF(mMessage);
                os.flush();
                message.clear();
                message.requestFocus();
                System.out.println("Message sent");
                if (!client.isConnected()) {
                    System.out.println("Server disconnected");
                }
            } catch (IOException e) {
                Alert error = new Alert(AlertType.ERROR, "Unable to send message. err: " + e.getMessage());
                error.show();
            }
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            // Socket Thread
            Thread socket = new SocketClient();
            socket.start();
        } catch (Exception e) {}
    }    

    public class SocketClient extends Thread {
        private boolean sysOk = true;
        private String message;

        SocketClient () {
            try {
                client = new Socket(ChatClient.ip, ChatClient.port);
                in = new DataInputStream(client.getInputStream());
                os = new DataOutputStream(client.getOutputStream());

                Alert confirm = new Alert(AlertType.CONFIRMATION, 
                    "Connected to " + client.getInetAddress() +
                            " at " + ChatClient.port);
                confirm.show();

            } catch(IOException e) {
                sysOk = false;
                Alert wentWrong = new Alert(AlertType.ERROR, 
                    "Something went wrong while establishing connection");
                wentWrong.show();
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            if (sysOk) {
                while (true) {
                    try {
                        if (in.available() > 0) {
                            try {
                                setMessage(in.readUTF());
                                Platform.runLater(new Runnable () {
                                    @Override
                                    public void run () {                                                messageArea.getItems().add(getMessage());
                                    }
                                });
                            } catch (Exception e) {
                                Alert messageRetrieveError = new Alert(
                                AlertType.ERROR, "Message Retrieval Failled");
                                messageRetrieveError.show();
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException e) {}
                }
            } 
        }

        private void setMessage(String data) {
            this.message = data;
        } 

        private String getMessage() {
            return this.message;
        }
    }
}

所以当我在某个端口创建服务器时说6000并尝试使用客户端软件连接它。它不起作用。我尝试从服务器软件发送一些消息,在第二次我得到:软件导致连接中止:套接字写入错误

我认为问题在于客户端代码,因为我尝试使用具有控制台客户端版本的服务器,并且它没有任何缺陷。

错误: 在服务器端:

    java.net.SocketException:软件导致连接中止:套接字写入错误     at java.net.SocketOutputStream.socketWrite0(Native Method)     在java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)     在java.net.SocketOutputStream.write(SocketOutputStream.java:153)     在java.io.DataOutputStream.write(DataOutputStream.java:107)     at java.io.DataOutputStream.writeUTF(DataOutputStream.java:401)     at java.io.DataOutputStream.writeUTF(DataOutputStream.java:323)     在chatserver.ChatController.sendMessage(ChatController.java:39)     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(未知来源)     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)     在javafx.fxml.FXMLLoader $ MethodHandler.invoke(FXMLLoader.java:1769)     在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)     在com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)     在com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)     在javafx.event.Event.fireEvent(Event.java:198)     在javafx.scene.Node.fireEvent(Node.java:8413)     在javafx.scene.control.Button.fire(Button.java:185)     at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)     at com.sun.javafx.scene.control.skin.BehaviorSkinBase $ 1.handle(BehaviorSkinBase.java:96)     at com.sun.javafx.scene.control.skin.BehaviorSkinBase $ 1.handle(BehaviorSkinBase.java:89)     at com.sun.javafx.event.CompositeEventHandler $ NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)     at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)     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)     在com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)     在com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)     在javafx.event.Event.fireEvent(Event.java:198)     在javafx.scene.Scene $ MouseHandler.process(Scene.java:3757)     在javafx.scene.Scene $ MouseHandler.access $ 1500(Scene.java:3485)     在javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)     在javafx.scene.Scene $ ScenePeerListener.mouseEvent(Scene.java:2494)     at com.sun.javafx.tk.quantum.GlassViewEventHandler $ MouseEventNotification.run(GlassViewEventHandler.java:380)     at com.sun.javafx.tk.quantum.GlassViewEventHandler $ MouseEventNotification.run(GlassViewEventHandler.java:294)     at java.security.AccessController.doPrivileged(Native Method)     at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda $ handleMouseEvent $ 354(GlassViewEventHandler.java:416)     at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)     at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)     在com.sun.glass.ui.View.handleMouseEvent(View.java:555)     在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 $ null $ 148(WinApplication.java:191)     在java.lang.Thread.run(Thread.java:745)

当我第二次发送消息时.. 客户端没有错误。

请帮我解决这个问题。
对这个不好的书面代码感到厌烦

0 个答案:

没有答案