jayp
jayp

Reputation: 21

Java Chat System

I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused Client:

    public void initializeConnection(){
    try {
        host = InetAddress.getLocalHost();
        try{
              // Create file 
              FileWriter fstream = new FileWriter("src/out.txt", true);
              BufferedWriter out = new BufferedWriter(fstream);
              out.write(host.getHostAddress()+'\n');
              //Close the output stream
              out.close();
          }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
          }
        clientSocket = new Socket(host.getHostAddress(), port);
        outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    }
    catch(IOException ioEx) {
        ioEx.printStackTrace();
    } 
}

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()==quit){
        try {
            outToServer.close();
            clientSocket.close();
            System.exit(1);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    else if(e.getSource()==button){ 
        if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
            String message = outMsgArea.getText();
            outToServer.println(clientName+": "+message);
            outMsgArea.setText("");
        }
    }
}

public void run(){
    try {
        while(true){
            String message = inFromServer.readLine();
            System.out.println(message);
                inMsgArea.append(message+'\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Server:

import java.io.*;
import java.net.*;
import java.util.*;

public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
  try{
    server = new ServerSocket(port);
  } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
  }
  while(true){
    ClientWorker w;
    try{
//server.accept returns a client connection
      w = new ClientWorker(server.accept());
      Thread t = new Thread(w);
      t.start();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
  }
}

protected void finalize(){
    //Objects created in run method are finalized when
    //program terminates and thread exits
         try{
            server.close();
        } catch (IOException e) {
            System.out.println("Could not close socket");
            System.exit(-1);
        }
      }

public static void main(String[] args) {
    new RelayChatServer().listenSocket();
}

}

class ClientWorker implements Runnable {
  private Socket client;

//Constructor
  ClientWorker(Socket client) {
    this.client = client;
  }

  public void run(){
    String line;
BufferedReader in = null;
PrintWriter out = null;
try{
  in = new BufferedReader(new 
    InputStreamReader(client.getInputStream()));
  //out = new 
  //  PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
  System.out.println("in or out failed");
  System.exit(-1);
}

while(true){
  try{
    line = in.readLine();
//Send data back to client
    //out.println(line);
//Append data to text area
    if(line!=null && line!=""){
        System.out.println(line);
    try{
          // Open the file that is the first 
          // command line parameter
          FileInputStream fstream = new FileInputStream("out.txt");
          BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
          String strLine;
          //Read File Line By Line
          Socket s;
          PrintWriter prnt;
          while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "")   {
          // Print the content on the console
              s = new Socket(strLine, 44441);
              prnt = new PrintWriter(s.getOutputStream(),true);
              prnt.println(line);
              System.out.println(strLine);
              prnt.close();
              s.close();
          }
          //Close the input stream
          //inp.close();
            }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }
    }
   }catch (IOException e) {
    System.out.println("Read failed");
    e.printStackTrace();
    System.exit(-1);
   }
}
  }

}

The Exception starts:

java.net.ConnectException: Connection refused: connect

The expanded output looks like:

enter image description here

Upvotes: 2

Views: 1140

Answers (1)

dbotha
dbotha

Reputation: 1693

I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps

s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);

should be:

prnt = new PrintWriter(client.getOutputStream(),true);

As currently I don't see where you are sending anything back to the client.

Edit: ok try something like the following:

static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {

    private Socket socket;
    private PrintWriter writer;

    ClientWorker(Socket socket) {
        this.socket = socket;
        try {
            this.writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException ex) { /* do something sensible */ }
    }

    public void run() {
        synchronized(connectedClients) {
            connectedClients.add(this);
        }

        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) { /* do something sensible */ }

        while (true) {
            try {
                String line = in.readLine();
                if (line != null && line != "") {
                    synchronized (connectedClients) {
                        for (int i = 0; i < connectedClients.size(); ++i){
                            ClientWorker client = connectedClients.get(i);
                            client.writer.println(line);
                        }
                    }
                }
            } catch (IOException e) { /* do something sensible */ }
        }
    }
}

Upvotes: 1

Related Questions