Hey Everyone,
This is my first post. Recently, I have been working on an instant messenger program in java. I have created the networking part of the client, and I have almost finished the server side. I know the program works and I am allowed to send messages, but now I am thinking about adding a feature that lets the user see who else is connected to the server, but i can not think of how to do this. Anyone have any ideas?

Do you intent to allow the client A to see all the other clients who are logged in .
I think you should use broadcast from the server to clients whenever a new client gets added or leaves. The server must already be maintaing the list of clients.
Also whenever the new client gets added , the server should send him the list of all logged clients.

cheers,
aj.wh.ca

I do want all other clients to see who is logged in. I was originally thinking that I would save all names to a linked list... but the problem I am having is that I can not figure out how I am going to send the username to the server from the client, and then I can't figure out how to get the server to conitinuousely update who has logged in/off and then send the list back to the client.

I do want all other clients to see who is logged in. I was originally thinking that I would save all names to a linked list... but the problem I am having is that I can not figure out how I am going to send the username to the server from the client, and then I can't figure out how to get the server to conitinuousely update who has logged in/off and then send the list back to the client.

Are you using TCP or UDP sockets for networking. mostly for instant messenger people use UDP.
As per your saying -- "I can not figure out how I am going to send the username to the server from the client".
I really do not understand what is the problem in this. If you are implementing some thing like yahoo messenger then the very first step from your client to server would be authenticating the user name.
I think I could help more if you specify more details. And what exactly you looking for -- code , logic, idea ?

I was using a TCP connection.... But I may look at UDP... I'm not going through yahoo or aim or anything else, I am basically just setting up my client to connect to another server that just receives the message and relays it back to everyone else signed in.

Here is the code for my server program.

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

public class Server
{
	ArrayList clientOutputStreams;
	
	public void go()
	{
		clientOutputStreams = new ArrayList();
		
		try
		{
			ServerSocket serverSock = new ServerSocket(4999);
			
			while (true)
			{ // set up the server writer function and then begin at the same
			  // the listener using the Runnable and Thread
				Socket clientSock = serverSock.accept();
				PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
				clientOutputStreams.add(writer);
				
				// use a Runnable to start a 'second main method that will run
				// the listener
				Thread listener = new Thread(new ClientHandler(clientSock));
				listener.start();
				System.out.println("got a connection");
			} // end while
		} // end try
		catch (Exception ex)
		{
			System.out.println("error making a connection");
		} // end catch
		
	} // end go()
	
	public class ClientHandler implements Runnable
	{
		BufferedReader reader;
		Socket sock;
		
		public ClientHandler(Socket clientSocket)
		{ // new inputStreamReader and then add it to a BufferedReader
			
			try
			{
				sock = clientSocket;
				InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
				reader = new BufferedReader(isReader);
			} // end try
			catch (Exception ex)
			{
				System.out.println("error beginning StreamReader");
			} // end catch
			
		} // end ClientHandler()
		
		public void run()
		{
			String message;
			
			try
			{
				while ((message = reader.readLine()) != null)
				{
					System.out.println("read" + message);
					tellEveryone(message);
				} // end while
			} // end try
			catch (Exception ex)
			{
				System.out.println("lost a connection");
			} // end catch
		} // end run()
	} // end class ClientHandler
	
	public void tellEveryone(String message)
	{ // sends message to everyone connected to server
		Iterator it = clientOutputStreams.iterator();
		
		while (it.hasNext())
		{
			try
			{
				PrintWriter writer = (PrintWriter) it.next();
				writer.println(message);
				writer.flush();
			} // end try
			catch (Exception ex)
			{
				System.out.println("error telling everyone");
			} // end catch
		} // end while
	} // end tellEveryone()
} // end class Server

OK I see your code. But as far as I understand you have not implemented any user mechanism in your server. So basically any once with the client program can connect to your server. Now coming back to your requirement for "a feature that lets the user see who else is connected to the server" you must implement a user name based feature so that when the client sends a connection request to your server, it must authenticate using a unique id. Otherwise with current approach all you can tell your clients is which all IP Address are live at a particular moment.

dear,
if you have made the messenger program in java. please send it to me i need it. i need it as soon as possible,thanks,
please e-mail it to me at my e-mail adress <email snipped>
i shall be very grateful to you for this.

is this code is runable like msn or yahoo messenger?? if you have made the messenger like yahoo or msn then please send me its code at my e-mail adress <email snipped> thanks.

My messenger program just set up its own server and went off that completely independent from aim or yahoo... I never fully got it to work though because I have Cox as my internet provider and they don't allow me to set up a server without upgrading my account to a business account,

I am creating messenger with java and I am creating it with Database and TCP/IP protocol. I have problem in sign in members with Database and with creating JTree in JTree Class.what should i do? please help me.

It is my Server code and LoginDialog code
It dosent work and dosent sign in . please help me or complete it.

import java.net.*;
import java.io.*;
import java.sql.*;
class Server {
   String line;
   ServerSocket server=null;
   BufferedReader in = null;
   PrintWriter out = null;
   Socket client = null;
   Connection cn;
   Statement st;
   ResultSet rs;
 public static void main(String args[]){
		Server st=new Server();
		st.listenSocket();
 }
 public void listenSocket(){
                   /*************DB Section******************/
                   try {
                       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                       cn = DriverManager.getConnection("jdbc:odbc:MessengerDB");
                       st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                       String Query = "SELECT * FROM Table2";
                       rs = st.executeQuery(Query);
                   } catch (ClassNotFoundException e) {
                       e.printStackTrace();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
                   /*****************************************/
	       try{
	         server = new ServerSocket(4444);
	       } catch (IOException e) {
	         System.out.println("Could not listen on port 4444");
	         System.exit(-1);
	       }
	       try{
	         client = server.accept();
	       } catch (IOException e) {
	         System.out.println("Accept failed: 4444");
	         System.exit(-1);
	       }
	       try{
	         in = new BufferedReader(new InputStreamReader(client.getInputStream()));
	         out = new PrintWriter(client.getOutputStream(), true);
	       } catch (IOException e) {
	         System.out.println("Accept failed: 4444");
	         System.exit(-1);
	       }
               try {
                   line = in.readLine();
                   if(line.equals("ok")) {
                       try {
                              out.println(rs.getString(1));
                              out.println(rs.getString(2));
                       } catch (SQLException e1) {
                        e1.printStackTrace();
                         }
                   }
               } catch (IOException e) {
                 e.printStackTrace();
                 }
 }
}

It is Login Dialog

//LoginDialog Class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class LoginDialog extends JDialog implements ActionListener,Constants{
	 String Username=null,Password=null,Server=null;
	 JLabel label1,label2,label3,label4;
	 JTextField user,server,port;
	 JPasswordField password;
     JButton ok,cancel;
    Socket client = null;
    ServerSocket ss=null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line;
//Constructor
 public LoginDialog(){	
		Container container = getContentPane();
		container.setLayout(new FlowLayout(FlowLayout.LEFT));
		label1= new JLabel("Login name :");
		label1.setBounds(10,10,80,20);
		label2= new JLabel("  Password :");
		label2.setBounds(10,40,80,20);
		user= new JTextField(20);
		user.setBounds(100,10,100,20);
		password=new JPasswordField(20);
		password.setBounds(100,40,100,20);
		label3= new JLabel("    Server :");
		label3.setBounds(10,70,80,20);
		label4= new JLabel("      Port :");
		label4.setBounds(10,100,80,20);
		server= new JTextField(SERVER_HOST);
		server.setBounds(100,70,100,20);
		port=new JTextField(SERVER_PORT+"");
		port.setBounds(100,100,100,20);
		port.setEditable(true);
		ok=new JButton("Login");
		ok.setBounds(30,130,70,20);
		cancel= new JButton("Cancel");
		cancel.setBounds(110,130,80,20);

		container.add(label1);
		container.add(user);
		container.add(label2);
		container.add(password);
		container.add(label3);
		container.add(server);
		container.add(label4);
		container.add(port);
		container.add(ok);
		container.add(cancel);

		user.addActionListener(this);
		password.addActionListener(this);
		server.addActionListener(this);
		port.addActionListener(this);
		ok.addActionListener(this);
		cancel.addActionListener(this);
        setSize(250,210);
        setLocation(400,250);
}
	public void actionPerformed(ActionEvent e)
	{
        if((e.getSource() == ok) || (e.getSource() == password)
        	||(e.getSource() == user) || (e.getSource() == server) ) {
			Username = user.getText();
			Password = new String(password.getPassword());
			Server = server.getText();			
			if(Server.length()== 0){
				JOptionPane.showMessageDialog(this,
				"Invalid server host","Error",
						JOptionPane.WARNING_MESSAGE);
				return;
			}
            setVisible(false);  //for OK Button of LoginDialog Class
         }
            else if(e.getSource() == cancel)
		    setVisible(false);
        if(e.getSource()==ok){
//Send data over socket
          String text =(ok.getText());
//create socket connection
     try{
          client = new Socket("localhost",4444);
        } catch (IOException e1) {
          System.out.println("Could not listen on port 4444");
          System.exit(-1);
        }
        try{
          in = new BufferedReader(new InputStreamReader(client.getInputStream()));
          out = new PrintWriter(client.getOutputStream(), true);
          out.println(text);
          String line1 = in.readLine();
          String line2 = in.readLine();
              if (line1.equals(user.getText())) {
                  user.setText(line1);
                  password.setText(line2);
              }
        } catch (IOException e1) {
          System.out.println("Accept failed: 4444");
          System.exit(-1);
        }
     }
    }
}

hey,
I am trying to develop an instant messenger on lines of yahoo ....
jus started out buh have hit a few roadblocks ... and I am new to java too and this is and application I am developing to learn java.

Some problems I am facing are:

1. I have mulitple functions like userLogin and registerNewUser etc in my client ... and I use an objectwriter stream ... so how can i tell on the server as to wht operation is to be performed.

2. I have to maintain a list of contacts for a perticular user ... each user has a unique Id. so what can be the most efficient way to do this ... storing all info for each user will take lots of space ...

3. In C# there is a mechanism to create a UUID ... this is also availabe in java 5.0 buh i could not find any such mechnism in java 1.40...

thanks!!

Mark

ok, what i've done on my little chat thingy is quite "basic". i have my server running and then a client would log in and the server would take the username and see if anyone is connected with that name yet(stores them in a vector - too busy at work to start making it more complex with a database and passwords and stuff, but that will come).

what you need to do, is if a user logs in, then send out a list of all the logged in users to the clients(i keep them in a vector in my server app and then run a method that sends out data to each of them). your clients should then take that list (something like "<users>bob-_-steve-_-billy-_-john-_-") and break it up with StringTokenizer(there they're separated with "-_-", but you can use anthing you like that you think would be unique) and just add that to the JList in your app or whatever you use to display the users(use a vector to store those usernames in and then just use userList.setListData( userVector ) to update the list).

if someone disconnects, then you send out a list again and your clients would then see if anything new is added or if anything isn't there and then update the list.

does that make it any clearer?

i've got my program, but haven't got a use for it yet. anyone want to buy it? :)

Hi everyone,

I am developing a peer-to-peer file transfer system. And I also had to maintain user names and their information in the server for later use. You can save the user info by creating a thread which sends user info to the server. And the server must have a thread running to receive the information...This is for sending info to server...

And you can use multicasting to send a message to all clients simultaneously...I implemented the mechanism, but the problem is multicasting allows only 224.0.0.1 to 239.255.255.255-- these IP addresses to use...I used 228.6.7.8. But lots of exceptions were generated and said that this IP address can't be used? Cannot I use localhost to implement multicasting? What do you guys think?

Best of luck

Razib

Hey This was very interesting to read, I had been wondering for a long time on how to make a IM of my own but this really does not help much could someone show me where to go to learn about this style of coding plz it would help me out alot thanx's

Hey This was very interesting to read, I had been wondering for a long time on how to make a IM of my own but this really does not help much could someone show me where to go to learn about this style of coding plz it would help me out alot thanx's

I got the initial part of my design out of a book called "Head First Java". They had a simple Instant messager client and server in there and I just added to it and modified it as I learned more.

Nick

am trying 2 create a messnger..
but dont kw hw 2 strt can n1 plzz help me
my mail id is
<snipped>
plzz help me
thnxx a lott

I am also trying to create an instant messaging program. If anyone has advice I would much appreciate it. My email address is <snipped>

You may find it in school library if you look for it, is one of common titles
and NO there is not electronic version, if there is then it is illegal

Sorry piyali, I only understand English grammar. Since nobody is aware of Google, I decided to be a nice guy and find some resources for all of you.

http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
http://www.cise.ufl.edu/~amyles/tcpchat/
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html


Once you know how to use the socket classes and understand the functionality of an instant messenger program, then you'll be able to write a simple chat client without too much difficulty. If you wish to create a client over an existing chat network, that's a whole other issue.

Comments
I search google; it brings me to this post.
NIce resources, but they expected us to do they homework :)
This article has been dead for over six months. Start a new discussion instead.