Hello every one in this video I will show you how to create local chat room in java. In this article I used socket by create socket object. follow my source code :
for Server Side :
package Ex1;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class server extends JFrame implements Runnable
{
ServerSocket ss;
Socket s[];
Thread t[];
BufferedReader br[];
PrintWriter pw[];
String st;
int num=0;
public server()
{
//setLayout(newFlowLayout(0));
s=new Socket[10];
t=new Thread[10];
br=new BufferedReader[10];
pw=new PrintWriter[10];
try {ss=new ServerSocket(5);
while(true)
{
s[num]=ss.accept();
br[num]=new BufferedReader(new InputStreamReader(s[num].getInputStream()));
pw[num]=new PrintWriter(s[num].getOutputStream(),true);
t[num]=new Thread(this);
t[num].start();
System.out.println(num+" Enter the room");
num++;
}
}
catch(Exception ee)
{
System.out.println("1"+ee);
}
}
public void run()
{
try {
while(true)
{
for (int i=0;i<num;i++)
{
if(Thread.currentThread()==t[i])
{
st=br[i].readLine();
char c[]=st.toCharArray();
String su=""+c[0];
int cl=Integer.parseInt(su);
System.out.println(cl);
int k=i+1;
if(cl==0)
{
for(int j=0;j<num;j++)
{
pw[j].println("Client "+k+": : :"+st);
}
}
else
{
pw[cl-1].println("Client "+k+": : :"+st);
}
}
}
}
}
catch(Exception ee)
{
System.out.println(ee);
}
}
public static void main(String arg[])
{
new server();
}
}
Client Side
package Ex1;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class client extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
Socket s;
BufferedReader br;
PrintWriter pw;
String st,st1,st2;
JTextArea ta;
JTextField tf,tf1;
JButton b1;
public client()
{
try {
setLayout(new FlowLayout(0));
ta=new JTextArea(10,25);
add(ta);
tf1=new JTextField(5);
add(tf1);
tf=new JTextField(25);
add(tf);
b1=new JButton("Send");
add(b1);
b1.addActionListener(this);
setVisible(true);
setSize(300,275);
setTitle("Client");
s=new Socket("localhost",5);
pw=new PrintWriter(s.getOutputStream(),true);
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true)
{
st2=br.readLine();
ta.append("\n"+st2);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public void actionPerformed(ActionEvent ee)
{
if(ee.getSource()==b1)
{
try {
st1=tf1.getText();
st=tf.getText();
ta.append("\n"+st);
pw.println(st1+st);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String arg[])
{
new client();
}
}