Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message from server to client

Tags:

java

I am trying to make an chatprogram in Java, when I send message on the client side the server side gets the message. But when I send from the server side to the client it do not get the message.

I cannot see what I am doing wrong.

The server side code:

private void serverStart(){
    textArea.append("Starting server " + " \n");

    try {
        serverSocket = new ServerSocket(4444);
        textArea.append("Waiting for Clients " + " \n");

        //Reading message from the client
        socket = serverSocket.accept();

        textArea.append("Client Connected " + "\n");

        //Send message to client 
        out = new PrintWriter(socket.getOutputStream());
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (true)
        {        

            messageFromClient = in.readLine();
            whileChat(messageFromClient); 
        }
    } catch(IOException ioExecption) {
        ioExecption.printStackTrace();
    }
}

private void whileChat(String messageFromClient) {
    showMessage(messageFromClient);
    System.out.println("Message from client : " + messageFromClient);
}

protected static void showMessage(final String message) {
    SwingUtilities.invokeLater( 
    new Runnable(){
        public void run()
        {
            Gui.consoleTextArea.append(message + "\n");
        }
    });
}

public static void sendMessage(String message) {
    out.println(message);
    showMessage(name +  " : " + message + "\n");
}

The Client side :

private void connectToServer() {

    try {
        socket = new Socket("localhost", 4444);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Thread clientThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // attach to socket's output stream with auto flush turned on
                //Send message to the server
                out = new PrintWriter(socket.getOutputStream(),
                        true);

                //Get return message from server
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                messageFromServer = in.readLine();
                whileChatting(messageFromServer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    clientThread.start();
}

private void whileChatting(String messageFromServer) {
    showMessage(messageFromServer);
    System.out.println("Message from server to client " + messageFromServer);
}

public static void Send(String msg) {
    out.println(name + " : " + msg);
    showMessage(name +  " : " + msg + "\n");
}
protected static void showMessage(final String message) {
    SwingUtilities.invokeLater( 
    new Runnable(){
        public void run(){
            Gui.consoleTextArea.append(message);
        }
    });
}

Hope someone could help me with this problem.

like image 627
tinaw25 Avatar asked Aug 20 '15 08:08

tinaw25


People also ask

How to send messages over a connection?

Use Async how tell Vincent Kuhlmann, and for send from server messages for many clientes basically use a array of Clients and send message all that is connected. The best way to send messages over a connection depends on what you're trying to do. Your current code "blocks" till the message is send, also know as synchronously.

Is it possible to send and receive data from the client?

It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from. We need additional streams both at server and client.

What is server to client socket messaging?

The Server to Client socket messaging is independent of which section page a user is on. Whichever client side schemas has code to receive those messages, It will be received in all those pages.

How does a server and client work together?

The client (web browser) requests for a task to be done asynchronously at the server side, then the client leaves it behind. When the server finishes the task, it will notify the client by sending some message.


1 Answers

You could perform a flush on the PrintWriter immediately after each println, or even better: Instance the PrintWriter with autoFlush=true:

out = new PrintWriter(socket.getOutputStream(), true);

In this way, each time you call println, printf, or format, the PrintWriter will perform a flush of the buffer at the end.

like image 136
Little Santi Avatar answered Nov 15 '22 12:11

Little Santi