0
votes

This code is supposed to make a ServerSocket and eventually a Client who can connect to the server. The problem is that all the messages I send are shown when the disconnect event is called, meaning when the Socket is closed. I want the messages to appear instantly when the send event is called everytime. How is this possible?

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
Who is reading this stream?RealSkeptic

1 Answers

0
votes

You need to use multiple threads. The server socket blocks while listening. Oracle has a good tutorial on this found here: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html

To make a simple chat client in Java: One thread acts as the 'server' and listens, one thread acts as the 'client' and speaks.