有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

sockets Java中的简单服务器客户端聊天?

这段代码应该是一个ServerSocket,最终是一个可以连接到服务器的客户机。问题是,我发送的所有消息都会在调用disconnect事件时显示,这意味着当socket关闭时。我希望每次调用send事件时消息都能立即显示。这怎么可能

package application;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class NController {
@FXML
public Button disconnect;
@FXML
public Button send;
@FXML
private TextArea history;
@FXML
private TextField chat;
public static OutputStream s1out;
public static BufferedWriter bf;
public static Socket s1;
public static ServerSocket s;

@FXML
public void initialize() {
    s = null;
    try {
        s = new ServerSocket(9000);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        s1 = s.accept();
        history.setText("Connected " + s1.getLocalAddress()
                + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
    send.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
            try {
                s1out = s1.getOutputStream();
                bf = new BufferedWriter(new OutputStreamWriter(s1out));
                history.appendText(s1.getLocalAddress().getHostName()
                        + ": " + chat.getText() + "\n");
                bf.write(s1.getLocalAddress().getHostName() + ": "
                        + chat.getText() + "\n");
                bf.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            chat.clear();
        }
    });
    disconnect.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
            send.isDisabled();
            try {
                s1.close();
                bf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

}


共 (0) 个答案