简体   繁体   中英

Listen to multiple InputStreams?

I am in the processes of making a Chat Program in Java in style with IM programs like MSN. Now, my program won't be near as full of features as MSN is, nor will i dive into the extensive GUI design either.

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. Basically, users make contact with the server and are kept in "limbo" until they decide to invite someone to a chat. 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. How would I manage to listen on all InputStreams and update when one of them "sends a message" to the Session?

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:

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. 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 ). Or try to use async IO with NIO.

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