Results 1 to 10 of 10
  1. #1
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465

    Default chat server w/ multiple clients. java


    i'm currently new to socket programming. and i would appreciate if someone tries to help me.
    here is the case, i'm successful to make this chat program only with 1 to 1. i mean 1 server to 1 client only, back and forth. and i'm not contented, i wanna learn how 1 server to multiple clients or back and forth works. i've read that i'll use thread for the server to wait for client to connect and another thread
    that start the streams and chatting when the connection has established. i've seen some codes about this one, but it only confuses me, so i try to create my own.
    i think the problem is on the server. here is the code of the server.

    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package jairoh.core.java.server;
    
    
    import jairoh.core.java.ui.ChatUI;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    import javax.swing.SwingUtilities;
    
    
    /**
     *
     * @author jairoh
     */
    public class Server {
        
        private ServerSocket ss;
        private Socket connection;
        private Scanner in;
        private Writer output;
        private ChatUI ui;
        
        public Server () {
            ui = new ChatUI( "SERVER - END");
            
            
            
            try { 
                
                ss = new ServerSocket( 1234, 100 );
                connection = ss.accept();
    
    
                in = new Scanner( new InputStreamReader ( connection.getInputStream() ) ); //read stream inputs
                output = new OutputStreamWriter( connection.getOutputStream() ); //sends stream outputs
                
                
                new Connect().start();
                new Streams().start();
              
                 
            } catch ( IOException e ) {
                System.out.println( e.getMessage() );
            }
            
        }
        
        private class Connect extends Thread {
            public void run () {
                while ( true ) {
                    try {
                        connection = ss.accept();
                        Thread.sleep( 500 );
                        
                    } catch ( IOException e ) {
                        System.out.println( e.getMessage() );
                    } catch ( InterruptedException e ) {
                        System.out.println( e.getMessage() );
                    }
                }
            }
        }
        
        private class Streams extends Thread {
            public void run () {
                while ( true ) {
                    try {
                        Thread.sleep( 500 );
                        in = new Scanner( new InputStreamReader ( connection.getInputStream() ) ); //read stream inputs
                        output = new OutputStreamWriter( connection.getOutputStream() ); //sends stream outputs
    
    
                        ui.output = output;
    
    
                        //read input streams and append to textarea; infinite loop until connection was lost
                        String msg;
                        while ( ( msg = in.nextLine() ) != null ) {
                            ui.appendText( msg );
                        }
    
    
                        
                    } catch ( IOException e ) {
                        System.out.println( e.getMessage() );
                    } catch ( InterruptedException e ) {
                        System.out.println( e.getMessage() );
                    }
                }
            }
        }
        
        
        public static void main ( String args [] ) throws IOException {
            new Server();
        }
    }
    english na ha kai i posted it somewhere nya wala pai nakatabang nako ani. so ni post ko dri.
    @mods if i'm violating something pls turn this post down. tnx

  2. #2
    onsa man imong wa ma sabtan sa code TS?

    as per my analysis.. ang code naa siya somesort of "timer"(nga mo sleep every 500ms) nga mag sigi og check kong kinsa nag connect og onsa ang sulod sa stream.

  3. #3
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465
    Quote Originally Posted by silent-kill View Post
    onsa man imong wa ma sabtan sa code TS?

    as per my analysis.. ang code naa siya somesort of "timer"(nga mo sleep every 500ms) nga mag sigi og check kong kinsa nag connect og onsa ang sulod sa stream.
    yes kasabot ko because i made that code. pero nganung di man japun mu.work ug multiple?

  4. #4
    Junior Member
    Join Date
    Jun 2009
    Gender
    Male
    Posts
    478
    many clients in just one channel? or you can have many channels just like in IRC?

  5. #5
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465
    Quote Originally Posted by kamsky View Post
    many clients in just one channel? or you can have many channels just like in IRC?
    one channel i think. i'm still learning socket boss. sorry

  6. #6
    dili ba dapat 1 person = 1 connection? sa imong case mura mag imong gi share tanan.

  7. #7
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465
    Quote Originally Posted by silent-kill View Post
    dili ba dapat 1 person = 1 connection? sa imong case mura mag imong gi share tanan.
    what do you mean boss? 1 client to 1 server?
    ako gi.mean kai 1 server = multiple connections/ clients. still learning. libog pako

  8. #8
    Just create a server, dedicated server bro...

    Ang dedicated server would listen to command..
    Connecting Clients - Inform Clients naa mo-sulod, update the list of clients
    Messages From Clients - Inform Clients naa'y message

    Kato sa akong g-PM last time nga naa'y mo-serve sa mga communication procedures.

    If you put timer, mag sige refresh ang timer, unlike kung maminaw ra sa port, deretso niya hatag ang information,
    di na mo-hulat sa next 500ms to update.

    Himuan nya tika diagram unsa akong pasabot.. kay padung ko lakaw.

  9. #9
    Junior Member
    Join Date
    Jun 2009
    Gender
    Male
    Posts
    478
    Here the quick and dirty of multi-user chat bro.

    Classes
    * Main server socket -- creates client socket, client thread, and holds the maps of the chatter
    * Client thread Runnable - prompt you to welcome, broadcast message to chatters

    Usage:
    1) Complie and run it
    2) run 'telnet localhost 5000' at least 2 instances

    I know there are problems but i think it's good enough for you to start. Let me know if you have more question.

    Code:
    package chat;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * 
     * @author kamsky
     *
     */
    public class ChatServer {
    	private ServerSocket serverSocket;
    	final int PORT = 5000;
    
    	// holds the value of the chatters
    	private Map<String, Client> clients = new HashMap<String, Client>();
    
    	public ChatServer() {
    		try {
    			System.out.println("Starting server listening at port: " + PORT);
    			serverSocket = new ServerSocket(PORT);
    			Socket socket = null;
    			while ((socket = serverSocket.accept()) != null) {
    				// creates a thread for every client
    				Client client = new Client(socket, clients);
    				Thread clientThread = new Thread(client);
    				clientThread.start();
    			}
    
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (serverSocket != null) {
    				try {
    					serverSocket.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    
    	}
    
    	public static void main(String[] args) {
    		new ChatServer();
    		Thread.currentThread().setDaemon(true);
    	}
    
    }
    
    /**
     * 
     * @author kamsky
     *
     */
    class Client implements Runnable {
    	private Socket socket;
    	private String name;
    	private Map<String, Client> clients;
    
    	/*
    	 * Client's socket and the party
    	 */
    	public Client(Socket socket, Map<String, Client> clients) {
    		this.socket = socket;
    		this.clients = clients;
    	}
    
    	/**
    	 * 
    	 * @return
    	 */
    	public Socket getSocket() {
    		return this.socket;
    	}
    
    	@Override
    	public void run() {
    		try {
    			// welcome message or authentication
    			System.out.println("Conneting " + socket);
    			OutputStreamWriter writer;
    			try {
    				writer = new OutputStreamWriter(socket.getOutputStream());
    				writer.write("Welcome! Enter your name: ");
    				writer.flush();
    				InputStreamReader isReader = new InputStreamReader(
    						socket.getInputStream());
    
    				BufferedReader reader = new BufferedReader(isReader);
    				String name = reader.readLine();
    
    				if (clients.get(name) == null) {
    					this.name = name;
    					clients.put(name, this);
    					broadcastMessage(name + " has joined ");
    
    				} else {
    					writer.write("Name " + name
    							+ " is taken. Please try again. Goodbye!");
    					writer.flush();
    					socket.close();
    				}
    
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    
    			// the exchanging of messages here
    			InputStreamReader isReader = new InputStreamReader(
    					socket.getInputStream());
    			BufferedReader reader = new BufferedReader(isReader);
    			String line = null;
    			while ((line = reader.readLine()) != null) {
    				// name : <message>
    				broadcastMessage("<" + this.name + "> : " + line);
    			}
    
    		} catch (IOException e) {
    			System.out.println("Connection closed ...");
    		}
    	}
    
    	/**
    	 *  simplified message 
    	 */
    	private void broadcastMessage(String message) throws IOException {
    		System.out.println("Message: " + message);
    		Set<String> clientsName = clients.keySet();
    		for (String name : clientsName) {
    			if (!this.name.equals(name)) {
    				// get the reader
    				Socket clientSocket = clients.get(name).getSocket();
    				OutputStreamWriter writer = new OutputStreamWriter(
    						clientSocket.getOutputStream());
    				writer.write(message);
    				writer.write("\r\n");
    				writer.flush();
    			}
    		}
    
    		// add prompt
    		OutputStreamWriter writer = new OutputStreamWriter(
    				socket.getOutputStream());
    		writer.write(">>");
    		writer.flush();
    	}
    }

  10. #10
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465
    Quote Originally Posted by kamsky View Post
    Here the quick and dirty of multi-user chat bro.

    Classes
    * Main server socket -- creates client socket, client thread, and holds the maps of the chatter
    * Client thread Runnable - prompt you to welcome, broadcast message to chatters

    Usage:
    1) Complie and run it
    2) run 'telnet localhost 5000' at least 2 instances

    I know there are problems but i think it's good enough for you to start. Let me know if you have more question.

    Code:
    package chat;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * 
     * @author kamsky
     *
     */
    public class ChatServer {
    	private ServerSocket serverSocket;
    	final int PORT = 5000;
    
    	// holds the value of the chatters
    	private Map<String, Client> clients = new HashMap<String, Client>();
    
    	public ChatServer() {
    		try {
    			System.out.println("Starting server listening at port: " + PORT);
    			serverSocket = new ServerSocket(PORT);
    			Socket socket = null;
    			while ((socket = serverSocket.accept()) != null) {
    				// creates a thread for every client
    				Client client = new Client(socket, clients);
    				Thread clientThread = new Thread(client);
    				clientThread.start();
    			}
    
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (serverSocket != null) {
    				try {
    					serverSocket.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    
    	}
    
    	public static void main(String[] args) {
    		new ChatServer();
    		Thread.currentThread().setDaemon(true);
    	}
    
    }
    
    /**
     * 
     * @author kamsky
     *
     */
    class Client implements Runnable {
    	private Socket socket;
    	private String name;
    	private Map<String, Client> clients;
    
    	/*
    	 * Client's socket and the party
    	 */
    	public Client(Socket socket, Map<String, Client> clients) {
    		this.socket = socket;
    		this.clients = clients;
    	}
    
    	/**
    	 * 
    	 * @return
    	 */
    	public Socket getSocket() {
    		return this.socket;
    	}
    
    	@Override
    	public void run() {
    		try {
    			// welcome message or authentication
    			System.out.println("Conneting " + socket);
    			OutputStreamWriter writer;
    			try {
    				writer = new OutputStreamWriter(socket.getOutputStream());
    				writer.write("Welcome! Enter your name: ");
    				writer.flush();
    				InputStreamReader isReader = new InputStreamReader(
    						socket.getInputStream());
    
    				BufferedReader reader = new BufferedReader(isReader);
    				String name = reader.readLine();
    
    				if (clients.get(name) == null) {
    					this.name = name;
    					clients.put(name, this);
    					broadcastMessage(name + " has joined ");
    
    				} else {
    					writer.write("Name " + name
    							+ " is taken. Please try again. Goodbye!");
    					writer.flush();
    					socket.close();
    				}
    
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    
    			// the exchanging of messages here
    			InputStreamReader isReader = new InputStreamReader(
    					socket.getInputStream());
    			BufferedReader reader = new BufferedReader(isReader);
    			String line = null;
    			while ((line = reader.readLine()) != null) {
    				// name : <message>
    				broadcastMessage("<" + this.name + "> : " + line);
    			}
    
    		} catch (IOException e) {
    			System.out.println("Connection closed ...");
    		}
    	}
    
    	/**
    	 *  simplified message 
    	 */
    	private void broadcastMessage(String message) throws IOException {
    		System.out.println("Message: " + message);
    		Set<String> clientsName = clients.keySet();
    		for (String name : clientsName) {
    			if (!this.name.equals(name)) {
    				// get the reader
    				Socket clientSocket = clients.get(name).getSocket();
    				OutputStreamWriter writer = new OutputStreamWriter(
    						clientSocket.getOutputStream());
    				writer.write(message);
    				writer.write("\r\n");
    				writer.flush();
    			}
    		}
    
    		// add prompt
    		OutputStreamWriter writer = new OutputStreamWriter(
    				socket.getOutputStream());
    		writer.write(">>");
    		writer.flush();
    	}
    }
    tnx boss. i'll study your code.

  11.    Advertisement

Similar Threads

 
  1. client to client chat in java.
    By jairoh_ in forum Programming
    Replies: 14
    Last Post: 05-21-2013, 11:15 AM
  2. Chat java. Naloko na c client.
    By jairoh_ in forum Programming
    Replies: 2
    Last Post: 05-08-2013, 06:27 AM
  3. Windows server 2003 (Multiple network path)
    By AMD_earl in forum Networking & Internet
    Replies: 1
    Last Post: 10-05-2012, 03:16 PM
  4. Replies: 0
    Last Post: 09-20-2006, 02:04 PM
  5. Need your Advice About Server & client Setup.
    By inspector_ronan in forum Networking & Internet
    Replies: 4
    Last Post: 06-29-2006, 04:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
about us
We are the first Cebu Online Media.

iSTORYA.NET is Cebu's Biggest, Southern Philippines' Most Active, and the Philippines' Strongest Online Community!
follow us
#top