954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

creating an instant messenger program in java

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?

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

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

aj.wh.ca
Junior Poster in Training
53 posts since Mar 2005
Reputation Points: 12
Solved Threads: 1
 

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.

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 
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 ?

aj.wh.ca
Junior Poster in Training
53 posts since Mar 2005
Reputation Points: 12
Solved Threads: 1
 

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.

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

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
stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

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.

aj.wh.ca
Junior Poster in Training
53 posts since Mar 2005
Reputation Points: 12
Solved Threads: 1
 

Thanks for the help. I think I understand it now!

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

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
i shall be very grateful to you for this.

nausherwan644
Newbie Poster
2 posts since May 2005
Reputation Points: 10
Solved Threads: 0
 

please do NOT send it. Clearly they want it for homework.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

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 thanks.

nausherwan644
Newbie Poster
2 posts since May 2005
Reputation Points: 10
Solved Threads: 0
 
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

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,

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

stupidenator, PLEASE DO NOT SEND THE CODE!

Ghost
Posting Whiz
352 posts since Aug 2004
Reputation Points: 12
Solved Threads: 2
 

Don't worry... I'm not going to.

stupidenator
Junior Poster
192 posts since Mar 2005
Reputation Points: 18
Solved Threads: 4
 

Quit saying that!

EDIT: I guess he stopped, didn't read the second page.

mmiikkee12
Posting Whiz in Training
274 posts since Oct 2004
Reputation Points: 17
Solved Threads: 5
 

Quit saying that!

EDIT: I guess he stopped, didn't read the second page.

Nope! He just hasn't posted today.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

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.

amsjavan
Newbie Poster
3 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

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();
                 }
 }
}
amsjavan
Newbie Poster
3 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

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);
        }
     }
    }
}
amsjavan
Newbie Poster
3 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You