繁体   English   中英

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

[英]Simple Server Client Chat in 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();
            }
        }
    });
}

}

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

用Java创建一个简单的聊天客户端:一个线程充当“服务器”并监听,一个线程充当“客户端”并说话。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM