Java Chat

Tue Mar 18, 2008 10:57 pm

* Project Name:   Java Chat
* Programmer:   msi_333
* Type:   Network
* Technology:  Java
* IDE:   NetBeans
* Description:   This is the Chat program with Client and Server .
It include two projects Server and Chat.
Both of them are netBeans 5.5 project.
The executables file exits in dist folder in both projects

ServerChat.jar
ClientChat.jar



Idea Allow you multi client and single server . The Center Server we forward the massages to other clients in his stack.
1- one server.
2- multi-clients.

Server File Code :
java code
/*
* * Please Visit us at codemiles.com *
* This Program was Developed by codemiles.com forums Team
* * Please Don't Remove This Comment *
*/
package serverchat;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
*
* @author sami
*/
public class myFrame extends JFrame{

/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JButton Start = new JButton("Start Server!");
private server ChatServer;
private InetAddress ServerAddress ;

public myFrame() {
setTitle("Server");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Server History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(Start);



Start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

ChatServer=new server();
ChatServer.start();

}
});
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChatServer.SendMassage(ServerAddress.getHostName()+" < Server > "+UserText.getText());
}
});


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);


}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new myFrame();
}


public class server extends Thread {
private static final int PORT=9999;
private LinkedList Clients;
private ByteBuffer ReadBuffer;
private ByteBuffer WriteBuffer;
public ServerSocketChannel SSChan;
private Selector ReaderSelector;
private CharsetDecoder asciiDecoder;


public server() {
Clients=new LinkedList();
ReadBuffer=ByteBuffer.allocateDirect(300);
WriteBuffer=ByteBuffer.allocateDirect(300);
asciiDecoder = Charset.forName( "US-ASCII").newDecoder();
}

public void InitServer() {
try {
SSChan=ServerSocketChannel.open();
SSChan.configureBlocking(false);
ServerAddress=InetAddress.getLocalHost();
System.out.println(ServerAddress.toString());

SSChan.socket().bind(new InetSocketAddress(ServerAddress,PORT));

ReaderSelector=Selector.open();
ChatBox.setText(ServerAddress.getHostName()+"<Server> Started. \n");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void run() {
InitServer();

while(true) {
acceptNewConnection();

ReadMassage();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}


}
}

public void acceptNewConnection() {
SocketChannel newClient;
try {

while ((newClient = SSChan.accept()) != null) {
ChatServer.addClient(newClient);

sendBroadcastMessage(newClient,"Login from: " +newClient.socket().getInetAddress());

SendMassage(newClient,ServerAddress.getHostName()+"<server> welcome you !\n Note :To exit" +
" from server write 'quit' .\n");
}

} catch (IOException e) {
e.printStackTrace();
}

}

public void addClient(SocketChannel newClient) {
Clients.add(newClient);
try {
newClient.configureBlocking(false);
newClient.register(ReaderSelector,SelectionKey.OP_READ,new StringBuffer());

} catch (IOException ex) {
ex.printStackTrace();
}
}

public void SendMassage(SocketChannel client ,String messg) {
prepareBuffer(messg);
channelWrite(client);
}
public void SendMassage(String massg) {
if(Clients.size()>0) {
for(int i=0;i<Clients.size();i++) {
SocketChannel client=(SocketChannel)Clients.get(i);
SendMassage(client,massg);
}
}
}


public void prepareBuffer(String massg) {
WriteBuffer.clear();
WriteBuffer.put(massg.getBytes());
WriteBuffer.putChar('\n');
WriteBuffer.flip();
}

public void channelWrite(SocketChannel client) {
long num=0;
long len=WriteBuffer.remaining();
while(num!=len) {
try {
num+=client.write(WriteBuffer);

Thread.sleep(5);
} catch (IOException ex) {
ex.printStackTrace();
} catch(InterruptedException ex) {

}
}
WriteBuffer.rewind();
}

public void sendBroadcastMessage(SocketChannel client,String mesg) {
prepareBuffer(mesg);
Iterator i = Clients.iterator();
while (i.hasNext()) {
SocketChannel channel = (SocketChannel)i.next();
if (channel != client) {
channelWrite(channel);
}
}
}
public void ReadMassage() {
try {

ReaderSelector.selectNow();
Set readkeys=ReaderSelector.selectedKeys();
Iterator iter=readkeys.iterator();
while(iter.hasNext()) {
SelectionKey key=(SelectionKey) iter.next();
iter.remove();

SocketChannel client=(SocketChannel)key.channel();
ReadBuffer.clear();

long num=client.read(ReadBuffer);

if(num==-1) {
client.close();
Clients.remove(client);
sendBroadcastMessage(client,"logout: " +
client.socket().getInetAddress());

} else {

StringBuffer str=(StringBuffer)key.attachment();
ReadBuffer.flip();
String data= asciiDecoder.decode(ReadBuffer).toString();
ReadBuffer.clear();

str.append(data);

String line = str.toString();
if ((line.indexOf("\n") != -1) || (line.indexOf("\r") != -1)) {
line = line.trim();
System.out.println(line);

if (line.endsWith("quit")) {
client.close();

Clients.remove(client);

ChatBox.append("Logout: " + client.socket().getInetAddress());

sendBroadcastMessage(client,"Logout: "
+ client.socket().getInetAddress());
ChatBox.append(""+'\n');
} else {
ChatBox.append(client.socket().getInetAddress() + ": " + line);

sendBroadcastMessage(client,client.socket().getInetAddress()
+ ": " + line);

ChatBox.append(""+'\n');

str.delete(0,str.length());
}
}
}
}

} catch (IOException ex) {
ex.printStackTrace();
}
}
}

}
/*
* * Please Visit us at codemiles.com *
* This Program was Developed by codemiles.com forums Team
* * Please Don't Remove This Comment *
*/

Client Code
java code
/*
* * Please Visit us at codemiles.com *
* This Program was Developed by codemiles.com forums Team
* * Please Don't Remove This Comment *
*/
package clientchat;



import com.sun.corba.se.spi.activation.RepositoryPackage.ServerDef;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
*
* @author sami
*/
public class myFrame extends JFrame{

/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JButton Start = new JButton("Connect");
private Client ChatClient;
private ReadThread myRead=new ReadThread();
private JTextField Server=new JTextField(20);
private JLabel myLabel=new JLabel("Server Name :");
private JTextField User=new JTextField(20);
private String ServerName;
private String UserName;


public myFrame() {
setResizable(false);
setTitle("Client");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Chat History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(Start);
cp.add(myLabel);
cp.add(Server);
cp.add(User);
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(ChatClient!=null) {

System.out.println(UserText.getText());
ChatClient.SendMassage(UserText.getText());
}
}
});
Start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChatClient=new Client();
ChatClient.start();
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);


}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new myFrame();
}


public class Client extends Thread {
private static final int PORT=9999;
private LinkedList Clients;
private ByteBuffer ReadBuffer;
private ByteBuffer writeBuffer;
private SocketChannel SChan;
private Selector ReadSelector;
private CharsetDecoder asciiDecoder;

public Client() {
Clients=new LinkedList();
ReadBuffer=ByteBuffer.allocateDirect(300);
writeBuffer=ByteBuffer.allocateDirect(300);
asciiDecoder = Charset.forName( "US-ASCII").newDecoder();
}

public void run() {

ServerName=Server.getText();
System.out.println(ServerName);
UserName=User.getText();

Connect(ServerName);
myRead.start();
while (true) {

ReadMassage();

try {
Thread.sleep(30);
} catch (InterruptedException ie){
}
}

}
public void Connect(String hostname) {
try {
ReadSelector = Selector.open();
InetAddress addr = InetAddress.getByName(hostname);
SChan = SocketChannel.open(new InetSocketAddress(addr, PORT));
SChan.configureBlocking(false);

SChan.register(ReadSelector, SelectionKey.OP_READ, new StringBuffer());
}

catch (Exception e) {
}
}
public void SendMassage(String messg) {
prepareBuffer(UserName+" says: "+messg);
channelWrite(SChan);
}


public void prepareBuffer(String massg) {
writeBuffer.clear();
writeBuffer.put(massg.getBytes());
writeBuffer.putChar('\n');
writeBuffer.flip();
}

public void channelWrite(SocketChannel client) {
long num=0;
long len=writeBuffer.remaining();
while(num!=len) {
try {
num+=SChan.write(writeBuffer);

Thread.sleep(5);
} catch (IOException ex) {
ex.printStackTrace();
} catch(InterruptedException ex) {

}

}
writeBuffer.rewind();
}

public void ReadMassage() {

try {

ReadSelector.selectNow();

Set readyKeys = ReadSelector.selectedKeys();

Iterator i = readyKeys.iterator();

while (i.hasNext()) {

SelectionKey key = (SelectionKey) i.next();
i.remove();
SocketChannel channel = (SocketChannel) key.channel();
ReadBuffer.clear();


long nbytes = channel.read(ReadBuffer);

if (nbytes == -1) {
ChatBox.append("You logged out !\n");
channel.close();
} else {

StringBuffer sb = (StringBuffer)key.attachment();

ReadBuffer.flip( );
String str = asciiDecoder.decode( ReadBuffer).toString( );
sb.append( str );
ReadBuffer.clear( );


String line = sb.toString();
if ((line.indexOf("\n") != -1) || (line.indexOf("\r") != -1)) {
line = line.trim();

ChatBox.append("> "+ line);
ChatBox.append(""+'\n');
sb.delete(0,sb.length());
}
}
}
} catch (IOException ioe) {
} catch (Exception e) {
}
}
}
class ReadThread extends Thread {
public void run() {
ChatClient.ReadMassage();
}
}
}
/*
* * Please Visit us at codemiles.com *
* This Program was Developed by codemiles.com forums Team
* * Please Don't Remove This Comment *
*/


chat.gif
Screenshot



Attachments
Chat.rar
Project code
(47.37 KiB) Downloaded 19308 times

Re: Java Chat

Fri Feb 13, 2009 7:12 pm

hey bro thx for this program

i'm looking for a program of chat between many client and the server

Re: Java Chat

Sat Feb 14, 2009 9:08 am

this do the job,

Re: Java Chat

Mon Feb 23, 2009 4:49 am

hello bro...
I am looking for voice chat with AES algorithm, if anybody has such a thing plz let me know

agin: Java Chat

Fri Mar 06, 2009 6:27 am

thanx for ur guidence but its not according to my requirements .
no IDE required.
console base application needed in java .

Re: Java Chat

Fri Mar 06, 2009 6:31 am

this file meet my requirements but not exist.
may i have other link for this same file .


The file ./../download/53_ece4e6e31167f0042d391a615cae44a9 does not exist.

Re: Java Chat

Fri Mar 06, 2009 9:22 am

i downloaded it , it works ...

Re: Java Chat

Sat Mar 07, 2009 9:29 am

Hi,
Thank you.
Where can I find the source files of this project?

Thanks in advance.

Re: Java Chat

Fri May 15, 2009 5:47 am

Thx

Re: Java Chat

Thu Oct 08, 2009 2:38 am

thanks for ur code

  Related Posts  to : Java Chat
 java chat program.     -  
 Java Chat With Customizable GUI     -  
 java code for chat     -  
 video chat application in java     -  
 Java Chat Program between two computers     -  
 Chat with Video Transmission in Java     -  
 Need Help for Java Chat - one server multiple clients..     -  
 chat system project in java using netbeans     -  
 Java Chat Program with client & Server     -  
 Chat Help     -  

Topic Tags

Java Projects, Java Networking