Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. Java
  4. Chat Server Issue

Chat Server Issue

Scheduled Pinned Locked Moved Java
helpcsharpjavasysadminlounge
18 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Joshua Waring

    So a method of non-blocking would be, upon return of the .accept(), we create a thread with the socket of the new user. Another thread could be used to send the received message to all the users, which i would think makes sending the received messages to one thread to be sent, let's say though a stack, instead to all threads where we wouldn't know when to peek and/or pop so messages are sent to all without missing users. To summaries, one thread per user to receive messages and one thread for all users to distribute them.

    P Offline
    P Offline
    pasztorpisti
    wrote on last edited by
    #5

    I detailed a solution/workaround with blocking sockets. Nonblocking sockets is a bit more complicated so search for a good tutorial if you want to learn it. In my workaround solution there is one thread per user, and 1 thread to accept new users. As I described in the solution the user thread sends the incoming messages to the user and then receives the message of the user. It does send some kind of data periodically (every half/one sec) even if there are no incoming messages or message sent by the user. The thread should have an array for incoming messages into which other user threads can put incoming messages. lets say a user thread receives a message from the user - in this case the user thread iterates over the other users and puts this message to their incoming message queue. The other user threads will send this message out to other clients when their thread gets into the state of "sending out incoming messages". You have to use locks on data structures that are used by multiple threads, for example on the list of users. This list is used by both the accept threads and the user threads. You also need to use a lock on the incoming message queue of user threads because it is accessed by both the user thread and other user threads who put messages to it.

    1 Reply Last reply
    0
    • B BobJanova

      If you're using blocking socket calls then you need a thread per client, and a thread for the server (if the server is a console application which does nothing else then that can be the main thread). accept and recv both block indefinitely so they need to be in separate threads. (send also blocks, but only for a short time so you don't need to worry about that in my experience.) You can use java.nio.* for asynchronous sockets. I've never used it but there are some examples here[^] and searching will turn things up.

      P Offline
      P Offline
      pasztorpisti
      wrote on last edited by
      #6

      Thinking it over again, a single threaded non-blocking solution might be easier to implement than a multithreaded blocking if someone has no experience with threading. I had a multithreaded async reactor pattern in my mind that put the async solution to a more difficult level than the blocking one... EDIT: I think the OP should try to write both solutions to get the feeling of it if he is interested!

      U 1 Reply Last reply
      0
      • P pasztorpisti

        Thinking it over again, a single threaded non-blocking solution might be easier to implement than a multithreaded blocking if someone has no experience with threading. I had a multithreaded async reactor pattern in my mind that put the async solution to a more difficult level than the blocking one... EDIT: I think the OP should try to write both solutions to get the feeling of it if he is interested!

        U Offline
        U Offline
        User 9293174
        wrote on last edited by
        #7

        What is a non blocking solution, how would it work?

        P 1 Reply Last reply
        0
        • U User 9293174

          What is a non blocking solution, how would it work?

          P Offline
          P Offline
          pasztorpisti
          wrote on last edited by
          #8

          I dont know how to do it in java so use google for java solutions. To get the grasp you can read these: http://www.scottklement.com/rpg/socktut/nonblocking.html[^] Blocking vs Non blocking socket calls in C++[^]

          J 1 Reply Last reply
          0
          • P pasztorpisti

            I dont know how to do it in java so use google for java solutions. To get the grasp you can read these: http://www.scottklement.com/rpg/socktut/nonblocking.html[^] Blocking vs Non blocking socket calls in C++[^]

            J Offline
            J Offline
            Joshua Waring
            wrote on last edited by
            #9

            OKAY so here comes the update, I've added it into threads but now a unknown error occurs. Thanks to a debugger I know where and when it occurs but I don't know why. I get a exceptionNullPointer at line 11 of Users.java br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

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

            public class Room implements Runnable{
            public void run(){
            ServerSocket serversocket;
            Socket socket;
            Clients client = new Clients();
            try{
            // Created a socket in which clients can connect to.
            serversocket = new ServerSocket(7776);
            // Waits for a client to connect to the server //
            while(true){
            socket = serversocket.accept();
            System.out.println("Client connected" + socket);
            // Starts their thread
            client.newThread(socket);
            }
            }catch(IOException e){
            System.out.println(e);
            }
            }
            public static void main(String[] args){
            (new Thread(new Room())).start();
            }
            }

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

            public class Clients implements Runnable{
            Socket socket1;
            public void run(){
            Socket socket2 = socket1;
            Users userfunction = new Users();
            BufferedReader bf;
            bf = userfunction.addStream(socket2);
            while(true){
            // Receives a Message.
            try{
            String out = bf.readLine();
            System.out.println(out);
            if(out != null)
            userfunction.sendMessageALL(out);

            		}catch(IOException e){
            			System.out.println(e);
            		}
            		try{
            			Thread.sleep(10);
            		} catch (InterruptedException e) {}
            	}
            }
            public void newThread(Socket socket){
            	// Creates one thread for ever client, to parse the socket I sent it to socket1 which is then
            	// received in the thread which is taken to socket2..
            	socket1 = socket;
            	(new Thread(new Clients())).start();
            }
            

            }

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

            public class Users {
            ArrayList recieveAL = new ArrayList();
            ArrayList sendAL = new ArrayList();
            // Creates the BufferedReader and PrintWriter then returns the Reader since the Writer it maintained in the class for the sendMessageAll method.
            public BufferedReader addStream(Socket socket){
            BufferedReader br;
            PrintWriter pw;
            try{
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream(), true);
            recieveAL.add(br);
            sendAL.

            P 2 Replies Last reply
            0
            • J Joshua Waring

              OKAY so here comes the update, I've added it into threads but now a unknown error occurs. Thanks to a debugger I know where and when it occurs but I don't know why. I get a exceptionNullPointer at line 11 of Users.java br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

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

              public class Room implements Runnable{
              public void run(){
              ServerSocket serversocket;
              Socket socket;
              Clients client = new Clients();
              try{
              // Created a socket in which clients can connect to.
              serversocket = new ServerSocket(7776);
              // Waits for a client to connect to the server //
              while(true){
              socket = serversocket.accept();
              System.out.println("Client connected" + socket);
              // Starts their thread
              client.newThread(socket);
              }
              }catch(IOException e){
              System.out.println(e);
              }
              }
              public static void main(String[] args){
              (new Thread(new Room())).start();
              }
              }

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

              public class Clients implements Runnable{
              Socket socket1;
              public void run(){
              Socket socket2 = socket1;
              Users userfunction = new Users();
              BufferedReader bf;
              bf = userfunction.addStream(socket2);
              while(true){
              // Receives a Message.
              try{
              String out = bf.readLine();
              System.out.println(out);
              if(out != null)
              userfunction.sendMessageALL(out);

              		}catch(IOException e){
              			System.out.println(e);
              		}
              		try{
              			Thread.sleep(10);
              		} catch (InterruptedException e) {}
              	}
              }
              public void newThread(Socket socket){
              	// Creates one thread for ever client, to parse the socket I sent it to socket1 which is then
              	// received in the thread which is taken to socket2..
              	socket1 = socket;
              	(new Thread(new Clients())).start();
              }
              

              }

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

              public class Users {
              ArrayList recieveAL = new ArrayList();
              ArrayList sendAL = new ArrayList();
              // Creates the BufferedReader and PrintWriter then returns the Reader since the Writer it maintained in the class for the sendMessageAll method.
              public BufferedReader addStream(Socket socket){
              BufferedReader br;
              PrintWriter pw;
              try{
              br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              pw = new PrintWriter(socket.getOutputStream(), true);
              recieveAL.add(br);
              sendAL.

              P Offline
              P Offline
              pasztorpisti
              wrote on last edited by
              #10

              probably because there is a null pointer there. why don't you debug your code?

              J 1 Reply Last reply
              0
              • J Joshua Waring

                OKAY so here comes the update, I've added it into threads but now a unknown error occurs. Thanks to a debugger I know where and when it occurs but I don't know why. I get a exceptionNullPointer at line 11 of Users.java br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

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

                public class Room implements Runnable{
                public void run(){
                ServerSocket serversocket;
                Socket socket;
                Clients client = new Clients();
                try{
                // Created a socket in which clients can connect to.
                serversocket = new ServerSocket(7776);
                // Waits for a client to connect to the server //
                while(true){
                socket = serversocket.accept();
                System.out.println("Client connected" + socket);
                // Starts their thread
                client.newThread(socket);
                }
                }catch(IOException e){
                System.out.println(e);
                }
                }
                public static void main(String[] args){
                (new Thread(new Room())).start();
                }
                }

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

                public class Clients implements Runnable{
                Socket socket1;
                public void run(){
                Socket socket2 = socket1;
                Users userfunction = new Users();
                BufferedReader bf;
                bf = userfunction.addStream(socket2);
                while(true){
                // Receives a Message.
                try{
                String out = bf.readLine();
                System.out.println(out);
                if(out != null)
                userfunction.sendMessageALL(out);

                		}catch(IOException e){
                			System.out.println(e);
                		}
                		try{
                			Thread.sleep(10);
                		} catch (InterruptedException e) {}
                	}
                }
                public void newThread(Socket socket){
                	// Creates one thread for ever client, to parse the socket I sent it to socket1 which is then
                	// received in the thread which is taken to socket2..
                	socket1 = socket;
                	(new Thread(new Clients())).start();
                }
                

                }

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

                public class Users {
                ArrayList recieveAL = new ArrayList();
                ArrayList sendAL = new ArrayList();
                // Creates the BufferedReader and PrintWriter then returns the Reader since the Writer it maintained in the class for the sendMessageAll method.
                public BufferedReader addStream(Socket socket){
                BufferedReader br;
                PrintWriter pw;
                try{
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream(), true);
                recieveAL.add(br);
                sendAL.

                P Offline
                P Offline
                pasztorpisti
                wrote on last edited by
                #11

                OK, here are a few suggestions: 1. I see you are coming from C because you declare all your function local variables at the beginning of the functions (sorry, methods). Declare your variables where you use it, or at least most most-inner scope where you need it. 2. Room does not have to implement the Runnable interface and you dont have to create a new thread for the room in your main(), call the run() method directly and execute it with the main thread. 3. The biggest mistake that causes the nullpointer is in Client.newThread: you should pass in this instead of new Clients(). I would do the work of Client.newThread in the constructor of Client and would create Client only after accepting the socket.

                J 1 Reply Last reply
                0
                • P pasztorpisti

                  probably because there is a null pointer there. why don't you debug your code?

                  J Offline
                  J Offline
                  Joshua Waring
                  wrote on last edited by
                  #12

                  A null pointer is when it returns a Null, right? I don't see the problem because that part of the code is unchanged. so why return an error now

                  P 1 Reply Last reply
                  0
                  • J Joshua Waring

                    A null pointer is when it returns a Null, right? I don't see the problem because that part of the code is unchanged. so why return an error now

                    P Offline
                    P Offline
                    pasztorpisti
                    wrote on last edited by
                    #13

                    You have a serious bug in your newThread() method that causes the nullpointer exception.

                    J 1 Reply Last reply
                    0
                    • P pasztorpisti

                      OK, here are a few suggestions: 1. I see you are coming from C because you declare all your function local variables at the beginning of the functions (sorry, methods). Declare your variables where you use it, or at least most most-inner scope where you need it. 2. Room does not have to implement the Runnable interface and you dont have to create a new thread for the room in your main(), call the run() method directly and execute it with the main thread. 3. The biggest mistake that causes the nullpointer is in Client.newThread: you should pass in this instead of new Clients(). I would do the work of Client.newThread in the constructor of Client and would create Client only after accepting the socket.

                      J Offline
                      J Offline
                      Joshua Waring
                      wrote on last edited by
                      #14

                      I really don't understand, this is currently beyond me at the moment.

                      P 1 Reply Last reply
                      0
                      • J Joshua Waring

                        I really don't understand, this is currently beyond me at the moment.

                        P Offline
                        P Offline
                        pasztorpisti
                        wrote on last edited by
                        #15

                        Well, object oriented programming is not easy at first. Socket/network programming is also hard. Threading is another beast. And you are mixing all of these, are you sure this is what you wanna do?

                        J 1 Reply Last reply
                        0
                        • P pasztorpisti

                          Well, object oriented programming is not easy at first. Socket/network programming is also hard. Threading is another beast. And you are mixing all of these, are you sure this is what you wanna do?

                          J Offline
                          J Offline
                          Joshua Waring
                          wrote on last edited by
                          #16

                          I'm committed to learn it and since I'm self taught, I've decided to throw myself in and learn how it all works then learn in more depth.

                          P 1 Reply Last reply
                          0
                          • J Joshua Waring

                            I'm committed to learn it and since I'm self taught, I've decided to throw myself in and learn how it all works then learn in more depth.

                            P Offline
                            P Offline
                            pasztorpisti
                            wrote on last edited by
                            #17

                            I don't recommend doing so, but good luck!

                            1 Reply Last reply
                            0
                            • P pasztorpisti

                              You have a serious bug in your newThread() method that causes the nullpointer exception.

                              J Offline
                              J Offline
                              Joshua Waring
                              wrote on last edited by
                              #18

                              Parsing the Socket into the thread was my screw up, so It was replaced with parameters of the thread.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups