GuidesUser Code: Java One-to-Many Chat

User Code: Java One-to-Many Chat

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Client Setting

/*
 
        Net Meeting.
   ______________ 
 
*/
 
/* Tips to run this :
    __________________
 
 (After compiling chatkaro12mserver.java)
 
 Step1: Open another prompt and run java chatkaro12mclient  127.0.0.1.
          ___________________________________   
 
   
*/ 

Server Setting

/*
 
          ** Net Meeting **
   __________________
 
*/
 
/* Tips to run this:
    __________________
 
  
 Step1: Open command prompt and run java chatkaro12mserver.
          ______________________   
 
 Step2: Continue with client program.
 
   
*/ 

Code: chatkaro12mserver.java

//  Program Starts...


import java.io.*;
import java.net.*;
import java.util.Vector;
import java.util.Enumeration;
public class chatkaro12mServer
{
	//static String k=socket.getInetAddress().getHostName();
	private int port=5001;
	private boolean li=true;
	private Vector clients=new Vector();
	public static void main(String a[])
	{
		System.out.println(" Press ctrl-c to Quit.");
		new chatkaro12mServer().server();
	}
	 void server()
	{
		ServerSocket serverSock=null;
		try 
		{
			InetAddress serverAddr=InetAddress.getByName(null);
			System.out.println("Waiting for"+serverAddr.getHostName()+"on port"+port);
			serverSock=new ServerSocket(port,50);
		}
		catch(IOException e)
		{
			System.out.println(e.getMessage()+":Failed");
			return;
		}
		while(li)
		{
			try
			{
				Socket socket=serverSock.accept();
				System.out.println("Accept "+socket.getInetAddress().getHostName());
				DataOutputStream remoteOut= new DataOutputStream(socket.getOutputStream());
				clients.addElement(remoteOut);
				new ServerHelper(socket,remoteOut,this).start();
			}
			catch(IOException e)
			{
				System.out.println(e.getMessage()+":Failed");
			}
		}
		if(serverSock !=null)
		{
			try
			{
				serverSock.close();
			}
			catch(IOException x)
			{
			}
		}
	}
	synchronized Vector getClients()
	{
		return clients;
	}
	synchronized void removeFromClients(DataOutputStream remoteOut)
	{	
		clients.removeElement(remoteOut);
	}
}
class ServerHelper extends Thread
{
	private Socket sock;
	private DataOutputStream remoteOut;
	private chatkaro12mServer server;
	private boolean li=true;
	private DataInputStream remoteIn;
	ServerHelper(Socket sock,DataOutputStream remoteOut,chatkaro12mServer server) throws IOException
	{
		this.sock=sock;
		this.remoteOut=remoteOut;
		this.server=server;
		remoteIn=new DataInputStream(sock.getInputStream());
	}
	public synchronized void run()
	{
		String s;
		try
		{
			while(li)
			{
				s=remoteIn.readUTF();
				broadcast(s);
			}
		}
		catch(IOException e)
		{	
			System.out.println(e.getMessage()+"connection lost");
		}
		finally
		{
			try
			{
				cleanUp();
			}
			catch (IOException x)
			{
			}
		}
	}
	private void broadcast(String s)
	{	
		Vector clients=server.getClients();
		DataOutputStream dataOut=null;
		for(Enumeration e=clients.elements();
		e.hasMoreElements(); )
		{
		dataOut=(DataOutputStream)(e.nextElement());
		if(!dataOut.equals(remoteOut))
		{
		try
		{
		dataOut.writeUTF(s);
		}
		catch(IOException x)
		{
		System.out.println(x.getMessage()+"Failed");
		server.removeFromClients(dataOut);
	}

}
}
}

private void cleanUp() throws IOException
{
	if(remoteOut!=null)
	{
		server.removeFromClients(remoteOut);
		remoteOut.close();
		remoteOut=null;
	}

	if(remoteIn!=null)
	{
		remoteIn.close();
		remoteIn=null;
	}

	if(sock!=null)
	{
		sock.close();
		sock=null;
	}
}
protected void finalize() throws Throwable
{
	try
	{
		cleanUp();
	}
	catch(IOException x)
	{
	}
	super.finalize();
}
}

Code: chatkaro12mclient.java

//  Program Starts...

import java.io.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class chatkaro12mClient extends Panel
{
TextArea receivedText;
Socket sock;
private GridBagConstraints c;
private GridBagLayout gridBag;
private Frame frame;
private Label label;
JButton send;
JButton exit;
private int port=5001;
private TextArea sendText;
private String hostname;
private String username;
private DataOutputStream remoteOut;
ImageIcon i1,i2;
public static void main(String args[])
{
if(args.length != 2)
{
System.out.println("Format is : java chatkaro12mClient  ");
return;
}
Frame f1=new Frame("Welcome Protocol");
f1.resize(800,600);
f1.show();
JOptionPane.showMessageDialog(f1,"Welcome "+args[0]+".. Have a nice Session.","Welcome",0);
Frame f= new Frame("Connecting to Mr. "+args[0]);
chatkaro12mClient chat=new chatkaro12mClient(f,args[0],args[1]);
f.add("Center",chat);
f.setSize(800,600);
f.show();
chat.client();
}
public chatkaro12mClient(Frame f,String user,String host)
{
frame=f;
frame.addWindowListener(new WindowExitHandler());
username=user;
hostname=host;
//Insets insets=new Insets(10,20,5,10);
//gridBag=new GridBagLayout();
//setLayout(gridBag);
/*c=new GridBagConstraints();
c.insets=insets;
c.gridy=0;
c.gridx=0;*/
label=new Label("Text to send :");
add(label);
/*gridBag.setConstraints(label,c);

c.gridx=1;*/
sendText=new TextArea(15,30);
/*sendText.addActionListener(new TextActionHandler());
gridBag.setConstraints(sendText,c);*/
add(sendText);
//c.gridy=1;
//c.gridx=0;
label= new Label("Text received :");
//gridBag.setConstraints(label,c);
add(label);
//c.gridx=1;
receivedText=new TextArea(15,30);
//gridBag.setConstraints(receivedText,c);
add(receivedText);
ImageIcon i1=new ImageIcon("click.gif");
ImageIcon i2=new ImageIcon("doorin2.gif");
send=new JButton(i1);
exit=new JButton(i2);
add(send);
add(exit);
send.addActionListener(new TextActionHandler());
exit.addActionListener(new EXIT());
}

void client()
{
try
{
	if(hostname.equals("local"))
		hostname=null;
	InetAddress serverAddr= InetAddress.getByName(hostname);
	sock=new Socket(serverAddr.getHostName(),port);
	remoteOut=new DataOutputStream(sock.getOutputStream());
	System.out.println("Connected to server " + serverAddr.getHostName() + " on port " + sock.getPort());
	new chatkaro12mClientReceive(this).start();
}
catch(IOException e)
	{
	System.out.println(e.getMessage() + " : Failed to connect to server.");
	}
}
protected void finalize() throws Throwable
{
try
{
	if(remoteOut != null)
		remoteOut.close();
	if(sock != null)
		sock.close();
}
catch(IOException x)
	{}
super.finalize();
}
class WindowExitHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window w=e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}

class EXIT implements ActionListener
 {
   public void actionPerformed(ActionEvent e)
  {
   if((JOptionPane.showConfirmDialog(new Frame(),"Are You Sure to close the Session?"))==JOptionPane.YES_OPTION)              
	{
	      JOptionPane.showMessageDialog(new Frame(),"Thank U. Visit Again. ","Good Bye",0);	
              System.exit(0);
	}
    	
  }
 }
class TextActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
remoteOut.writeUTF(sendText.getText());
JOptionPane.showMessageDialog(new Frame(),"Your msg has been sent ","Confirmation",0);
sendText.setText("");
}
catch(IOException x)
{
System.out.println(x.getMessage() + " : connection to peer lost.");
}
}
}
}
class chatkaro12mClientReceive extends Thread 
{
private chatkaro12mClient chat;
chatkaro12mClientReceive(chatkaro12mClient chat)
{
this.chat=chat;
}
public synchronized void run()
{
String s;
DataInputStream remoteIn=null;
try
{
	remoteIn= new DataInputStream(chat.sock.getInputStream());
while(true)
	{
	s=remoteIn.readUTF();
	chat.receivedText.setText(s);
	}
}
catch(IOException e)
{
System.out.println(e.getMessage() + " : connection to peer lost.");
}
finally
{
try
{
if(remoteIn !=null)
	remoteIn.close();
}
catch(IOException x)
{}
}
}
}

Downloads

    Download source file = 3K

    Download source file = 4K

See previous submission: User Code: ChatKaro

Dedication: To my Brothers and Sisters.

This code was contributed by
S. Balasubramanian. For more information, visit his site.

[To contribute a code article to Gamelan, please contact kmurphy@internet.com.]

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories