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

时间:2015-03-07 16:53:12

标签: java sockets client chat server

这段代码应该是一个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();
            }
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

您需要使用多个线程。侦听时服务器套接字阻塞。 Oracle在这里找到了一个很好的教程: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html

用Java创建一个简单的聊天客户端:一个线程充当&#39;服务器&#39;并且倾听,一个线程充当&#39;客户端&#39;说话。