MultiServerThreadFromClient.java 1.26 KB
Newer Older
Michele Fiori's avatar
Michele Fiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package chatRoom;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class MultiServerThreadFromClient extends Thread {
    private Socket s;
    private MultiQueue q;
    private DataOutputStream outToClient;
    private BufferedReader inFromClient;
    private int clientId;

    public MultiServerThreadFromClient(Socket s, MultiQueue q, int clientId) throws IOException {
        this.s = s;
        this.q = q;
        this.clientId = clientId;
        this.outToClient = new DataOutputStream(s.getOutputStream());
        this.inFromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
    }

    public void run() {
        while(true) {
            try {
                String msg = inFromClient.readLine();
                q.put(msg, clientId);
                System.out.println(clientId+": "+msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMsg(MultiMessage msg) throws IOException {
        if(msg.getClientId() != clientId) {
            outToClient.writeBytes(msg.getClientId()+": "+ msg.getMessage() + "\n");
        }
    }
}