简体   繁体   English

JAVA线程客户端的聊天程序

[英]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 :) 我仍然处于开发状态,这就是为什么我要在catch上使用运行时错误。.稍后将对此进行总结:)

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(); 当您调用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). 多数民众赞成在阻止调用,这意味着该程序将不会继续到下一行,直到服务器将发送以\\n结尾的字符串(一行)。 that also mean that writeMessage(output); 这也意味着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 因此,如果要使此客户端按需运行,则应实现2个线程,其中1个用于从服务器读取,而1个用于写入服务器

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

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