简体   繁体   English

听多个InputStreams?

[英]Listen to multiple InputStreams?

I am in the processes of making a Chat Program in Java in style with IM programs like MSN. 我正在用MSN之类的IM程序制作Java聊天程序。 Now, my program won't be near as full of features as MSN is, nor will i dive into the extensive GUI design either. 现在,我的程序不会像MSN那样具有那么多的功能,我也不会涉足广泛的GUI设计。

The problem I have is, that I might be going for the wrong kind of design to do this. 我的问题是,我可能会选择错误的设计来执行此操作。

I am currently designing a Session Object. 我目前正在设计一个Session对象。 Basically, users make contact with the server and are kept in "limbo" until they decide to invite someone to a chat. 基本上,用户与服务器建立联系并保持“ limbo”状态,直到他们决定邀请某人进行聊天为止。 Then it's the servers job (haven't gotten to that part yet) to establish a Session between the users involved. 然后是服务器工作(尚未完成该部分)在所涉及的用户之间建立会话。

My problem is, that I have to listen for changes in multiple InputStreams and update everyone's display accordingly. 我的问题是,我必须侦听多个InputStream中的更改并相应地更新每个人的显示。 How would I manage to listen on all InputStreams and update when one of them "sends a message" to the Session? 当其中一个向会话“发送消息”时,我如何设法监听所有InputStream并进行更新?

Here is my code so far. 到目前为止,这是我的代码。 It's not very long. 时间不长

package server; 包服务器;

import java.io.*;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 *
 * @author Vipar
 */
public class Session implements Runnable {
    private static User[] users;
    private static PrintWriter[] outputs;
    private int sessionId;

    public Session(User[] users) {
        this.users = users;
        outputs = new PrintWriter[users.length];
        sessionId = this.hashCode();

        try {
            for(int i = 0; i < users.length; i++) {
            outputs[i] = new PrintWriter(users[i].getSocket().getOutputStream(), true);
            }
        } catch (IOException ioe) {
            ChatServer.print("An error occured in session " + sessionId);
            ChatServer.print(ioe.getMessage());
        }
    }

    @Override
    public void run() {
        ChatServer.print("SessionId: " + sessionId + " have initiated.");
        ExecutorService service = Executors.newFixedThreadPool(users.length);
        for(int i = 0; i < users.length; i++) {
            service.submit(new InputStreamListener(users[i]));
        }
        do {
            if(users.length < 2) {
                ChatServer.print("SessionId: " + sessionId + " have ended.");
                break;
            }
        } while(true);
    }

    public static void update(User u, String message) {
        for(int i = 0; i < users.length; i++) {
            outputs[i].println("new");
            outputs[i].println(u.getUserName());
            outputs[i].println(message);
        }
    }
}

The InputStreamListener I just made: 我刚刚制作的InputStreamListener:

package server;

import java.util.Scanner;
import java.io.*;
import java.util.NoSuchElementException;

/**
 *
 * @author Vipar
 */
public class InputStreamListener implements Runnable {
    private Scanner scanner;
    private User user;
    public InputStreamListener(User user) {
        this.user = user;
        try {
            scanner = new Scanner(user.getSocket().getInputStream());
        } catch (IOException ioe) {
            ChatServer.print("An Error occured for the InputStream: "
                    + user.getUserName());
            ChatServer.print(ioe.getMessage());
        }

    }

    @Override
    public void run() {
        String s = "";
        do {
            try {
                s = scanner.nextLine();
                Session.update(user, s);
            } catch(NoSuchElementException e) {
                continue;
            }
        } while(!s.equals("/DISCONNECT"));
        try {
            user.getSocket().close();
        } catch(IOException ioe) {
            ChatServer.print("Problem closing users InputStream: "
                    + user.getUserName());
            ChatServer.print(ioe.getMessage());
        }
    }
}

The simplest approach is use one thread for each client. 最简单的方法是为每个客户端使用一个线程。 Each thread reads from its own InputStream and inform session about new messages. 每个线程从其自己的InputStream读取并向会话通知新消息。 Such thread also can know how to send messages back to client. 这样的线程还可以知道如何将消息发送回客户端。 If you expect many clients, you can try something more lightweight than thread, like actors (eg Akka ). 如果您期望有很多客户,则可以尝试比线程更轻量的东西,例如actor(例如Akka )。 Or try to use async IO with NIO. 或者尝试将异步IO与NIO结合使用。

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

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