简体   繁体   中英

JAVA thread client for chat program

I'm still trying to improve with doing these posts right. But here is my problem, and I know that its properly a small thing that I oversee... I got my server for this chat program up and running doing everything right, but my client is'nt working. I can write to server and nothing happens... when next message to server is send the answer from first message comes back. I'll upload my client under here and will be happy for any help you guys can offer..

I'm still in a development state on this and thats why I'm onlt using runtime errors on my catch'es.. This will later on be delt with :)

I'm only trying to get this to work by starting my server, starting two clients and try to get them to talk with eachother using the consol.

public class ChatClient implements Runnable {

private static final int PORT = 4711;
private static final String HOST = "localhost";
Socket socket = new Socket();
private final PrintWriter out;
private final BufferedReader in;
private final BufferedReader keyboard;
public static boolean running = true;

public ChatClient(Socket socket) throws IOException {
    this.socket = socket;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    keyboard = new BufferedReader(new InputStreamReader(System.in));
}

public static void main(String[] args) throws IOException {

    Socket socket = new Socket(HOST, PORT);
    ChatClient client = new ChatClient(socket);
    new Thread(client).start();
}

public void writeMessage(String message) {
    out.println(message);
    out.flush();
}

@Override
public void run() {
    String responseLine;
    while (true) {
        try {
            responseLine = in.readLine();
            if (!responseLine.isEmpty()) {
                System.out.println("<< " + responseLine);
            }
        } catch (IOException ioe) {
            throw new RuntimeException("ups", ioe);
        }

        try {
            String output = (String) keyboard.readLine();
            if (!output.isEmpty()) {

                writeMessage(output);
            }
        } catch (IOException ioe) {
            throw new RuntimeException("ups", ioe);
        }
    }
}

}

By request here is my server code

public class ChatServer implements Runnable {

public static final int PORT = 4711;
public static boolean running = true;
private final BufferedReader in;
private final PrintWriter out;
private final Socket socket;
public static final Map<String, Socket> userMap = new HashMap();

public ChatServer(Socket socket) throws IOException {

    this.socket = socket;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
}

public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(PORT);
    while (running) {
        System.out.println("Waiting for client to connect " + PORT);
        Socket socket = server.accept();
        ChatServer chat = new ChatServer(socket);
        //userMap.put("prøve", socket);
        new Thread(chat).start();

    }
}   

public void targetMessage(String target, String message) throws IOException {
    System.out.println("Target: " + target);
    System.out.println("KEYS: " + userMap.get(target));
    System.out.println("MAP: " + userMap.toString());
    System.out.println("USERS: " + userMap.keySet());

    if (userMap.containsKey(target)) {
        Socket s = userMap.get(target);
        ChatServer c = new ChatServer(s);
        c.out.println(message);
    } else {
        out.println("User does not exist or user is not online at the moment");
    }
}  

@Override
public void run() {

    try {
        out.println("Please connect to server writing CONNECT and then your username: ");
        String line = in.readLine();

        while (!line.isEmpty()) {
            InputSplit split = new InputSplit(line);
            switch (split.getCommand()) {
                case "CONNECT":
                    if (!split.getAlias().equals("ALL")) {
                        userMap.put(split.getAlias(), ChatServer.this.socket);
                        line = "You are connected as user: " + split.getAlias();
                        out.println(line);
                        System.out.println("user map size: " + userMap.size());
                        break;
                    } else {
                        out.println("Username can not be ALL");
                    }

                case "MESSAGE":
                    line = split.getMessage();
                    targetMessage(split.getAlias(), line);
                    System.out.println("line : " + line);
                    break;

            }
            line = in.readLine();
        }

    } catch (IOException ioe) {
        throw new RuntimeException("hovsa", ioe);
    }

}

}

When you call responseLine = in.readLine(); thats a blocking call, it means that the program will not continue to the next line untill the server will send a string ending with \\n (a line). that also mean that writeMessage(output); will be called only after the client gets something from the server.

so if you want to make this client work as you want it, you should implement 2 threads, 1 for read from server and 1 to write to server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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