Question

Hi i want to test if my client app is working by testing it on a very simple java server. My client will send a string almost every second. My idea is that the server will display the string in the eclipse console once it receives the string. But the problem is that the simple java server only prints out the first string. Below is the simple java server i got from the site

  package serverjava;

/* ChatServer.java */
import java.net.ServerSocket;
import java.net.Socket;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class serverjava {
    private static int port = 1234; /* port the server listens on */

    public static void main (String[] args) throws IOException {
        ServerSocket server = null;
        try {
            server = new ServerSocket(port); /* start listening on the port */
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + port);
            System.err.println(e);
            System.exit(1);
        }

        Socket client = null;
        try {
            client = server.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.err.println(e);
            System.exit(1);
        }

        /* obtain an input stream to the client */
        BufferedReader in = new BufferedReader(new InputStreamReader(
                    client.getInputStream()));

        String msg;
        /* loop reading lines from the client and display them */
        while ((msg = in.readLine()) != null) {
            System.out.println("Client says: " + msg);
        }
    }
}

Is the java server capable of displaying only an instance of a string per launch? If yes, how can I make it to print or show in the console all the strings that are being sent every second?

Was it helpful?

Solution

The problem you have is that you read the buffer only one time. The server waits for client lines and when it reads them, then it finish the execution because 'msg' is null. You must have a process that reads every second or minute, or hour... That means using THREADS.

Be careful! Don't use a while(true) structure of something like that, because the machine will be overloaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top