Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 38

Thread: Reply to all clients Multithreading

  1. #1
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Reply to all clients Multithreading

    I have a server/client written. At the moment it's replying to individual clients (User one receives user one's post only) and I need multiple users to receive all posts.


    Server

    import java.net.*;
    import java.io.*;
    import java.util.*;
     
    class ServerThread extends Thread{
    	private Socket socket;
     
    	ServerThread(Socket socket){
    		this.socket = socket;
    	}	
     
    	public void run(){
    		try
    		{
    			String message = null;
    			PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
    			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    			br.readLine();
    			while((message = br.readLine()) != null){ // while messages read them
    				pw.println(message);
    			}
     
    			socket.close();
     
    		}	
    			catch(IOException e)
    			{
    				System.out.println("Client disconnected");
    			}
    	}
    }
     
    // The server
    public class Server{
    	public static final int PORT = 7777;
    	public ArrayList<Socket> connections = new ArrayList<>();
     
    	public static void main(String[] args) throws IOException {
    			new Server().run();
    	}
     
    	public void run() throws IOException{
    		ServerSocket serverSocket = new ServerSocket(PORT); 			// wait for request from PORT
    		System.out.println("Server is listening for connections");			
     
    		while(true){
    			Socket socket = serverSocket.accept();						// listen and accept connection
    			connections.add(socket);
    			new ServerThread(socket).start();
    			System.out.println("Client " + connections.size());
    		}
    	}
    }

    Client

    import java.net.*;
    import java.io.*;
    import java.util.*;
     
     
     
    public class Client{
     
        public static void main(String[] args) throws UnknownHostException, IOException 
    	{
    		String name = args[0];
    		Socket socket = new Socket("localhost", 7777);
    		BufferedReader brFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
    		pw.println(name);
    		BufferedReader brFromCmd = new java.io.BufferedReader(new InputStreamReader(System.in));
     
    		while(true){
    			String readInput = brFromCmd.readLine();
    			pw.println(name + ": " + readInput);
    			System.out.println(brFromClient.readLine());
    		}
     
    	}
    }

    Any help is greatly appreciated..


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    Save a list of clients to send messages to. When sending a message, loop through the list and send the message to each client in the list.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    what would I use to hold the clients?

    a socket Array?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    Use an ArrayList to hold the objects needed to do the posts.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Sorry, I meant an ArrayList<Socket> ?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    You might want to keep more info about the connection than just the Socket. Define a class that contains the Socket and allows for other info about the client to be saved.
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    ManInTheMiddle (May 1st, 2013)

  8. #7
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Cheers, I'll give it a go. Much appreciated..

    --- Update ---

    I have, class ServerThread and class Server in my Server, can it be done in the ServerThread? As the ServerThread class holds the socket already .

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    can it be done
    What is the "it" that is to be done?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Quote Originally Posted by Norm View Post
    You might want to keep more info about the connection than just the Socket. Define a class that contains the Socket and allows for other info about the client to be saved.
    Can this be done in the ServerThread class?

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    It should be done where you want to save the data about a connection to a client.
    When a connection to the server is made, create an instance of the class with a reference to the Socket and save that in the list to be used for sending messages to connected clients.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    I came up with this Data Structure

    class CountConnections extends Thread{
    	private ArrayList<Socket> connections = new ArrayList<>();
    	private Socket socket;
     
    	CountConnections(){
    		socket = null;
    	}	
     
    	void add(Socket s){
    		connections.add(s);
    	}
     
    	void remove(Socket s){
    		connections.remove(s);
    	}
     
    	void print(){
    		System.out.println(connections.size());
    	}
    }

    If I add the information to the ArrayList then should be stored correctly for sending?

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    Why does the class extend Thread?
    How would that class be useful? The only thing it saves is a Socket. Is the all the info about a connection that needs to be saved? What about userid, status, last message received, message being sent,...? I don't know what the app might want to save about a client that is connected.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Actually, this class is just to save the number of connections. So, it displays on the server eg Client 1... Client 2...Client 3 then if someone leaves the chat it decrease eg. Client 2... Client 1 etc.. This is also in my assignment.

    Sorry, I moved to a different problem late last night.

    So, to send information to all clients userid, status, last message received and sent needs to be stored then sent?
    I'll have a go even though it's really sunny here in Ireland today haha and we don't get much of that

  15. #14
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Right, so, I'v come up with this

    class ServerStatus {
    	private final ArrayList<Socket> clients;
        private final ArrayList<String> names;
    	private final ArrayList<String> messages;
     
        public ServerState() {
        	this.clients = new ArrayList<Socket>();
        	this.names = new ArrayList<String>();
    		this.message = new ArrayList<String>();
        }
     
        public synchronized void addUser(String name, Socket client) {
        	this.clients.add(client);
        	this.names.add(name);
     
        }
     
        public void removeUser(String name, Socket client) throws IOException {
       		this.clients.remove(client);
       		this.names.remove(name);	
       		client.close();
        }
     
    	public synchronized void addMessage(String message) {
        	this.message.add(message);
        }
     
        public List<String> getUsers() {
        	return this.names;
        }
     
        public List<Socket> getClients() {
        	return this.clients;
        }
     
    	public List<String> getMessage() {
        	return this.messages;
        }
     
    }

    Would this work??

  16. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    Parallel arraylists are going to be a problem. Put all the data into one class and save an instance of that class in the arraylist.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #16
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    I don't quite follow. Can I add different data types ? As i'm adding Sockets and Strings.

    would I use?

    ArrayList<ClassName> ListName = new ArrayList<>();

  18. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    Something like this:
    class ClassToHoldData {
      SomeCls item1;
      SomeOtherCls item2;
      AnotherCls item3;
     
      ClassToHoldData(SomeCls i1, SomeOtherCls i2, AnotherCls ac) {
          item1 = i1;     //  save data in class variables
          item2 = i2;
          item3 = ac;
       } //  end constructor
     
       //  There would be getters and other methods here
     
    } // end class
     
    //  somewhere else in the code
       ArrayList<ClassToHoldData> listOfStuff = new ArrayList<>();
       ...
       listOfStuff.add(new ClassToHoldData(the data to be saved goes here));
    If you don't understand my answer, don't ignore it, ask a question.

  19. #18
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Ah cool, much appreciated man.. I've never coded like that before so it's a bit tricky to get my head around..

  20. #19
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    so, I'v come up with this but it's showing a NullPointerException. Any suggestions?

    class ServerThread extends Thread
    {
    	private Socket socket; 
    	private String name, message;
        private ArrayList <ServerThread> clientList;
    	private ArrayList <String> nameList;
    	private PrintWriter out; 
        private BufferedReader in;
     
    	public synchronized void sendToAll(String message)
    	{
        	for(ServerThread c: clientList)
    		{
    			c.out.println(message);				
    		}
        }
     
    	ServerThread(Socket socket, ArrayList <ServerThread> clientList)
    	{
        	super("ServerThread");
        	this.socket = socket;
        	this.clientList = clientList;
        }	
     
    	public void run(){
    		try
    		{
    			out = new PrintWriter(socket.getOutputStream(), true);	// be able to echo back message to client
    			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    			name = in.readLine();
     
    			if(!nameList.contains(name))
    			{
    				nameList.add(name);
    			}	
     
    			sendToAll( name + " has joined the chatroom ....\n");
     
    			while((message = in.readLine()) != null)
    			{ 			
    				sendToAll(name+": "+ message);	
    			}
     
    			clientList.remove(currentThread());
     
    			System.out.println("Clients :" +clientList.size() + "\n");
    			out.close();
    			in.close();
    			socket.close();
    		}	
    			catch(IOException e)
    			{
    				 e.printStackTrace();
    			}
    	}
    }
     
    // The server
    public class Server
    {
    	public static final int PORT = 7777;
    	private ArrayList <ServerThread> clientList = new ArrayList<>();
     
    	public static void main(String[] args) throws IOException {
    			new Server().run();
    	}
     
    	public void run() throws IOException{
    		ServerSocket serverSocket = new ServerSocket(PORT); 			// wait for request from PORT
    		System.out.println("Server is listening for connections...");			
     
    		while(true){
    			try{
    				Socket socket = serverSocket.accept();						
    				ServerThread client = new ServerThread(socket,clientList);
    				//add client to clientList and start the thread
    				clientList.add(client);
    				System.out.println("Clients :" + clientList.size() + "\n");
    				client.start();
    			} 
    			catch (IOException e)
    			{
    				e.getMessage();
    			}
     
    			serverSocket.close();
    		}
    	}
    }

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    it's showing a NullPointerException
    Copy the full text of the error message and paste it here.
    Find the variable with the null value and backtrack in the code to see why it does not have a valid value.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    Exception in thread "ServerThread" java.lang.NullPointerException
    at ServerThread.run(Server.java:36)

    it's the
    if(!nameList.contains(name)) // line 36
    			{
    				nameList.add(name);
    			}

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    What variable has the null value? Why doesn't it have a valid value?
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    It should be adding a Clients name if the name doesn't already exist, see previous post.

    I'v an ArrayList<String> nameList that should be getting the client from clientList.add(client);

    So, for some reason there is no data been added when I run a client

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Reply to all clients Multithreading

    What variable has the null value?
    An example of how to get a NPE:
      String aStr = null;
      int len = aAStr.length();  //   NPE here because aStr is null
    If you don't understand my answer, don't ignore it, ask a question.

  26. #25
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Reply to all clients Multithreading

    The private String name is null. But it should be receiving data from

                            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    			name = in.readLine();

Page 1 of 2 12 LastLast

Similar Threads

  1. Multithreading
    By Miths in forum Java Theory & Questions
    Replies: 10
    Last Post: December 17th, 2012, 02:46 AM
  2. Its urgent please reply soon
    By vikas.sharma in forum Web Frameworks
    Replies: 3
    Last Post: September 11th, 2012, 09:12 AM
  3. reply plz
    By Tanmaysinha in forum What's Wrong With My Code?
    Replies: 4
    Last Post: August 16th, 2011, 09:24 AM
  4. Am I right (urgent, please reply)
    By Sunil Raghuvanshi in forum The Cafe
    Replies: 2
    Last Post: March 26th, 2010, 07:05 AM

Tags for this Thread