Chat Program in Java

Here is the sample program for chatting with our friends and rest of us. Fell free to see the code and just try it out. And please post your comments as well.

chat.java

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class chat extends JFrame implements ActionListener
{
JPanel panel;
JScrollPane jsp;
JTextField tf;
JButton button;
static JTextArea ta;
ConnectionThread conn;
public chat() throws Exception
{
super(“Chat”);
panel=new JPanel();
ta=new JTextArea(10,40);
jsp=new JScrollPane(ta);
tf=new JTextField(33);
button=new JButton(“Send”);
conn=new ConnectionThread();
ta.setEditable(false);
panel.add(jsp);
panel.add(tf);
panel.add(button);
button.addActionListener(this);
getContentPane().add(panel);
setSize(500,300);
setVisible(true);
}
static void printReply(String str)
{
ta.setText(ta.getText()+”REMOTE PORT:”+str.trim()+”\n”);
}
public static void main(String args[]) throws Exception
{
new chat();
}
public void actionPerformed(ActionEvent e)
{
try
{
ta.setText(ta.getText()+tf.getText()+”\n”);
conn.write(tf.getText());
tf.setText(“”);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
class ConnectionThread extends Thread
{
DatagramSocket dgs;
DatagramPacket dgp;
static byte[] buf;
int sourceport,destport;
String ipaddress;
public ConnectionThread() throws Exception
{
ipaddress=JOptionPane.showInputDialog(“Enter remote machine’s IP address: (Press cancel if using the local machine)”);
sourceport=Integer.parseInt(JOptionPane.showInputDialog(“Enter source port:”));
destport=Integer.parseInt(JOptionPane.showInputDialog(“Enter destination port:”));
dgs=new DatagramSocket(sourceport);
buf=new byte[256];
dgp=new DatagramPacket(buf,buf.length);
start();
}
public void run()
{
try
{
while(true)
{
dgs.receive(dgp);
String received=new String(dgp.getData(),0);
chat.printReply(received);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void write(String str) throws Exception
{
buf=new byte[255];
str.getBytes(0,str.length(),buf,0);
DatagramPacket dgp=new DatagramPacket(buf,buf.length,InetAddress.getByName(ipaddress),destport);
dgs.send(dgp);
}
}
Advertisements