SlideShare a Scribd company logo
Hi, I need some one to help me with "Design a client-server Chat software using java or C, the
software should have sign up new user,and sign in user, send text, send file, and join chat room"
the more features the software has the better. tnx History u Messenge Serve server Database File
9/14/2012 9:01 PM XML Document 9/14/2012 10:33 AM Executable Jar File 9/14/2012 10:34
AM Executable Jar File Browse... Start Server 1 KB 48 KB Messenger Host Address localhost
Username Anurag History File ssage File Host Port 13000 Password Connect Sign Up Show
Send Message
Solution
Server Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.util.zip.GZIPOutputStream;
import javax.swing.SwingUtilities;
public class Server extends JFrame implements ActionListener {
public JList online;
private JTextField ipaddress, textMessage;
private JButton send, start, disconnect;
private JTextArea chatArea;
private JLabel port;
int client[] = new int[100];
private ObjectOutputStream out[] = new ObjectOutputStream[client.length+ 1];
private ObjectInputStream in[] = new ObjectInputStream[client.length+ 1];
String username[] = new String[client.length+1];
static String b;
public String nm, usm;
private ServerSocket server;
private Socket connect;
boolean success = true;
int id=0;
ArrayList UserList = new ArrayList();
public Server() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.setPreferredSize(new Dimension(650, 500));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.setBackground(Color.LIGHT_GRAY);
p.add(port = new JLabel("Port No"));
p.add(ipaddress = new JTextField("1500"));
p.add(start = new JButton("START"));
p.add(disconnect = new JButton("DISCONNECT"));
disconnect.setEnabled(false);
start.setBorderPainted(false);
start.setBackground(Color.yellow);
start.setForeground(Color.WHITE);
disconnect.setBorderPainted(false);
disconnect.setBackground(Color.yellow);
disconnect.setForeground(Color.WHITE);
ipaddress.setCaretPosition(0);
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.setBackground(Color.LIGHT_GRAY);
p1.add(chatArea = new JTextArea());
chatArea.setPreferredSize(new Dimension(300, 350));
chatArea.setLineWrap(true);
chatArea.setEditable(false);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.setBackground(Color.LIGHT_GRAY);
p2.add(textMessage = new JTextField(20));
p2.add(send = new JButton("SEND"));
send.setBackground(Color.blue);
send.setForeground(Color.WHITE);
send.setBorderPainted(false);
start.addActionListener(this);
send.addActionListener(this);
c.add(p, BorderLayout.NORTH);
c.add(p1, BorderLayout.CENTER);
c.add(p2, BorderLayout.SOUTH);
}
SimpleDateFormat log = new SimpleDateFormat("HH:mm");
String d = log.format(new Date());
public void Start() {
int portNo = 0;
try {
String no = ipaddress.getText();
portNo = Integer.parseInt(no);
chatArea.append("Connection to port " + portNo + "... ");
server = new ServerSocket(portNo);
success = true;
} catch (Exception ex) {
chatArea.append("Error cannot bind to port  ");
success = false;
}
if (success == true) {
addClient ob1 = new addClient("RunServer");
start.setEnabled(false);
disconnect.setEnabled(true);
}
}
public class addClient implements Runnable {
Thread t;
addClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
WaitClient();
} catch (Exception ex) {
break;
}
for (int i = 0; i < client.length; i++) {
if (client[i] == 0) {
client[i] = i + 1;
id = i;
break;
}
}
out[client[id]] = new ObjectOutputStream(connect.getOutputStream());
out[client[id]].flush();
in[client[id]] = new ObjectInputStream(connect.getInputStream());
chatArea.append(d + " Client:[" + client[id] + "] : Connected successful  ");
sendUser(client[id], "Connected to the server");
ChatMessage cm = (ChatMessage) in[client[id]].readObject();
handle(client[id], cm);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public synchronized void handle(int num, ChatMessage cm){
if(cm.type.equals("login")){
username[client[findClient(num)]] = cm.sender;
send(client[findClient(num)], new ChatMessage("login", "SERVER", "TRUE",
cm.sender));
Announce("newuser", "SERVER", cm.sender);
SendUserList(cm.sender);
}else if(cm.type.equals("message")){
if(cm.recipient.equals("All")){
Announce("message", cm.sender, cm.content);
}
else{
send(findUserThread(cm.recipient), new ChatMessage(cm.type, cm.sender,
cm.content, cm.recipient));
send(client[findClient(num)], new ChatMessage(cm.type, cm.sender, cm.content,
cm.recipient));
}
}
}
public void SendUserList(String toWhom){
for(int i = 0; i < id; i++){
send(findUserThread(toWhom), new ChatMessage("newuser", "SERVER",
username[client[i]], toWhom));
}
}
public int findUserThread(String usr){
for(int i = 0; i < id; i++){
if(username[client[i]].equals(usr)){
return client[i];
}
}
return id;
}
private int findClient(int n){
for (int i = 0; i < id; i++){
if (client[i] == n){
return client[i];
}
}
return id;
}
private void WaitClient() throws IOException {
chatArea.append(d + " : Waiting for connection...  ");
connect = server.accept();
chatArea.append(d + " : Now connected to " + connect.getInetAddress().getHostName() +
" ");
}
//send message to specific user
public void send(int number, ChatMessage cm) {
try {
out[number].writeObject(cm);
out[number].flush();
} catch (Exception e) {
}
}
public void sendUser(int number, String info) {
try {
out[number].writeObject(info);
out[number].flush();
} catch (Exception e) {
}
}
public void Announce(String type, String sender, String content){
ChatMessage cm = new ChatMessage(type, sender, content, "All");
for(int i = 0; i < id; i++){
send(client[i], cm);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == send) {
} else if (e.getSource() == start) {
Start();
}
if (e.getSource() == disconnect) {
}
}
}
Main class
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Main extends javax.swing.JFrame {
private ObjectOutputStream out;
private ObjectInputStream in;
static String b; //variable for message
private Socket join;
boolean success = true;
private String serverIP = "10.1.1.1"; ArrayList userlist = new ArrayList();
SimpleDateFormat log = new SimpleDateFormat("HH:mm");
String d = log.format(new Date());
public File file;
public String serverAddr, username, password;
DefaultListModel model = new DefaultListModel();
public Main() {
initComponents();
}
private void initComponents() {
jButton3 = new javax.swing.JButton();
start = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
textMessage = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
chatArea = new javax.swing.JTextArea();
usernm = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
send = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
online = new javax.swing.JList();
upload = new javax.swing.JButton();
filename = new javax.swing.JTextField();
stop = new javax.swing.JButton();
login = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
ip = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
portnumber = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
passwordfield = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("ICARE ");
setFocusable(false);
setPreferredSize(new java.awt.Dimension(840, 650));
setResizable(false);
getContentPane().setLayout(null);
jButton3.setText("Send");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(710, 110, 100, 30);
start.setBackground(new java.awt.Color(51, 51, 255));
start.setFont(new java.awt.Font("Tahoma", 0, 14));
start.setForeground(new java.awt.Color(255, 255, 255));
start.setText("Start");
start.setBorder(null);
start.setBorderPainted(false);
start.setRequestFocusEnabled(false);
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
}
});
getContentPane().add(start);
start.setBounds(20, 100, 90, 40);
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 0, 820, 0);
getContentPane().add(textMessage);
textMessage.setBounds(270, 450, 440, 70);
chatArea.setColumns(20);
chatArea.setFont(new java.awt.Font("Arial", 0, 14));
chatArea.setRows(5);
jScrollPane2.setViewportView(chatArea);
getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(270, 150, 540, 290);
getContentPane().add(usernm);
usernm.setBounds(540, 10, 170, 30);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
jLabel1.setText("Enter your nickname :");
getContentPane().add(jLabel1);
jLabel1.setBounds(380, 10, 160, 30);
send.setBackground(new java.awt.Color(51, 51, 255));
send.setFont(new java.awt.Font("Tahoma", 0, 14));
send.setForeground(new java.awt.Color(255, 255, 255));
send.setText("Send");
send.setBorder(null);
send.setBorderPainted(false);
send.setRequestFocusEnabled(false);
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendActionPerformed(evt);
}
});
getContentPane().add(send);
send.setBounds(720, 470, 90, 40);
online.setBackground(new java.awt.Color(0, 0, 0));
online.setFont(new java.awt.Font("Tahoma", 0, 12));
online.setForeground(new java.awt.Color(102, 255, 0));
jScrollPane3.setViewportView(online);
getContentPane().add(jScrollPane3);
jScrollPane3.setBounds(20, 150, 230, 370);
upload.setFont(new java.awt.Font("Tahoma", 0, 18));
upload.setText("+");
upload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uploadActionPerformed(evt);
}
});
getContentPane().add(upload);
upload.setBounds(650, 110, 50, 30);
getContentPane().add(filename);
filename.setBounds(270, 110, 370, 30);
stop.setBackground(new java.awt.Color(51, 51, 255));
stop.setFont(new java.awt.Font("Tahoma", 0, 14));
stop.setForeground(new java.awt.Color(255, 255, 255));
stop.setText("Log Out");
stop.setToolTipText("");
stop.setBorder(null);
stop.setBorderPainted(false);
stop.setRequestFocusEnabled(false);
stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopActionPerformed(evt);
}
});
getContentPane().add(stop);
stop.setBounds(720, 60, 90, 40);
login.setBackground(new java.awt.Color(51, 51, 255));
login.setFont(new java.awt.Font("Tahoma", 0, 14));
login.setForeground(new java.awt.Color(255, 255, 255));
login.setText("Log In");
login.setToolTipText("");
login.setBorder(null);
login.setBorderPainted(false);
login.setRequestFocusEnabled(false);
login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginActionPerformed(evt);
}
});
getContentPane().add(login);
login.setBounds(720, 10, 90, 40);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14));
jLabel3.setText("Port No :");
jLabel3.setToolTipText("");
getContentPane().add(jLabel3);
jLabel3.setBounds(20, 60, 100, 30);
getContentPane().add(ip);
ip.setBounds(110, 20, 150, 30);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14));
jLabel4.setText("IP Address :");
jLabel4.setToolTipText("");
getContentPane().add(jLabel4);
jLabel4.setBounds(20, 20, 100, 30);
getContentPane().add(portnumber);
portnumber.setBounds(110, 60, 150, 30);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel5.setText("Enter your
password :");
getContentPane().add(jLabel5);
jLabel5.setBounds(380, 60, 160, 30);
getContentPane().add(passwordfield);
passwordfield.setBounds(540, 60, 170, 30);
pack();
}
private void startActionPerformed(java.awt.event.ActionEvent evt) {
Start();
String group = "All";
online.setModel(model);
model.addElement(group);
online.setSelectedIndex(0);
send(new ChatMessage("test", "testUser", "testContent", "SERVER"));
}
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
String z = textMessage.getText();
String target = online.getSelectedValue().toString();
if(!z.isEmpty() && !target.isEmpty()){
textMessage.setText("");
send(new ChatMessage("message", username, z, target));
}
}
private void uploadActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showDialog(this, "Select File");
file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().isEmpty()) {
String str;
if (filename.getText().length() > 30) {
String t = file.getPath();
str = t.substring(0, 20) + " [...] " + t.substring(t.length() - 20, t.length());
} else {
str = file.getPath();
}
filename.setText(str);
}
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
long size = file.length();
if (size < 120 * 1024 * 1024) {
send(new ChatMessage("upload_req", username, file.getName(),
online.getSelectedValue().toString()));
} else {
chatArea.append("File is size too large ");
}
}
private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-
FIRST:event_stopActionPerformed
//
if (!username.isEmpty()) {
send(new ChatMessage("logout", username, password, "SERVER"));
}
}
private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-
FIRST:event_loginActionPerformed
username = usernm.getText();
password = passwordfield.getText();
if(!username.isEmpty() && !password.isEmpty()){
send(new ChatMessage("login", username, password, "SERVER"));
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
public javax.swing.JTextArea chatArea;
public javax.swing.JTextField filename;
public javax.swing.JTextField ip;
public javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
public javax.swing.JButton login;
public javax.swing.JList online;
public javax.swing.JPasswordField passwordfield;
public javax.swing.JTextField portnumber;
public javax.swing.JButton send;
public javax.swing.JButton start;
public javax.swing.JButton stop;
private javax.swing.JTextField textMessage;
public javax.swing.JButton upload;
public javax.swing.JTextField usernm;
public void Start() {
try {
start.setEnabled(false);
chatArea.append(d + " : Attempting connection...  ");
join = new Socket(serverAddr, 10500);
chatArea.append(d + " : Connected to - " + join.getInetAddress().getHostName() + "
");
success = true;
} catch (Exception ex) {
chatArea.append("Error cannot bind to port  ");
success = false;
}
if (success == true) {
ClientThread ct = new ClientThread();
}
}
class ClientThread implements Runnable {
ClientThread ct;
Thread t;
ClientThread() {
t = new Thread(this, "RunClient");
t.start();
}
public void run() {
try {
try {
out = new ObjectOutputStream(join.getOutputStream());
out.flush();
in = new ObjectInputStream(join.getInputStream());
b = (String) in.readObject();
chatArea.append(b + " ");
chatArea.setCaretPosition(chatArea.getText().length());
} catch (Exception e) { }
CThread c1 = new CThread();
} catch (Exception ex) { }
}
}
class CThread implements Runnable {
CThread ob1;
Thread t;
CThread() {
t = new Thread(this, "Message");
t.start();
}
public void run() {
try {
do {
try {
ChatMessage cm = (ChatMessage) in.readObject();
System.out.println("Incoming : "+cm.toString());
if(cm.type.equals("login")){
if(cm.content.equals("TRUE")){
chatArea.append("[SERVER > Me] : Login Successful ");
} else{
chatArea.append("[SERVER > Me] : Login Failed ");
}
} else if(cm.type.equals("test")){
start.setEnabled(false);
}else if(cm.type.equals("message")){
if(cm.recipient.equals(username)){
chatArea.append("["+cm.sender +" > Me] : " + cm.content + " ");
}
else{
chatArea.append("["+ cm.sender +" > "+ cm.recipient +"] : " + cm.content +
" ");
}
}else if(cm.type.equals("newuser")){
online.setModel(model);
model.addElement(cm.content);
}else if(cm.type.equals("upload_req")){
JFileChooser jf = new JFileChooser();
jf.setSelectedFile(new File(cm.content));
int returnVal = jf.showSaveDialog(this);
String saveTo = jf.getSelectedFile().getPath();
if(saveTo != null && returnVal == JFileChooser.APPROVE_OPTION){
Download dwn = new Download(saveTo);
Thread t = new Thread(dwn);
t.start();
send(new ChatMessage("upload_res", username,
(""+dwn.port), cm.sender));
}
else{
send(new ChatMessage("upload_res", username, "NO", cm.sender));
}
}
else if(cm.type.equals("upload_res")){
if(!cm.content.equals("NO")){
int port = Integer.parseInt(cm.content);
String addr = cm.sender;
Upload upl = new Upload(serverAddr, port, file);
Thread t = new Thread(upl);
t.start();
}
else{
chatArea.append("[SERVER > Me] : "+cm.sender+" rejected file request ");
}
}
else{
chatArea.append("[SERVER > Me] : Unknown message type ");
}
} catch (Exception ex) {
chatArea.append("Server is disconnected" + " ");
try {
in.close();
out.close();
join.close();
} catch (Exception ex2) { }
}
} while (!b.equalsIgnoreCase("bye"));
} catch (Exception ex) {
}
}
}
void send(ChatMessage cm) {
try {
out.writeObject(cm);
out.flush();
} catch (Exception e) {
}
}
}
Chat class
import java.io.Serializable;
public class Chat implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public Chat(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
@Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"',
recipient='"+recipient+"'}";
}
}

More Related Content

PDF
Laporan multiclient chatting client server
PDF
MultiClient chatting berbasis gambar
DOCX
Laporan multi client
PDF
Laporan multiclient chatting berbasis grafis (gambar)
PPT
Socket Programming
PDF
Multi client
DOCX
Multi client
PDF
Note Use Java Write a web server that is capable of processing only.pdf
Laporan multiclient chatting client server
MultiClient chatting berbasis gambar
Laporan multi client
Laporan multiclient chatting berbasis grafis (gambar)
Socket Programming
Multi client
Multi client
Note Use Java Write a web server that is capable of processing only.pdf

Similar to Hi, I need some one to help me with Design a client-server Chat so.pdf (20)

DOCX
JavaExamples
PDF
Server1
DOCX
201913046 wahyu septiansyah network programing
PDF
java sockets
PPT
香港六合彩 &raquo; SlideShare
PPT
Baocao Web Tech Java Mail
ODP
Networking and Data Access with Eqela
PDF
WebTalk - Implementing Web Services with a dedicated Java daemon
PDF
Creating a Whatsapp Clone - Part II.pdf
PDF
Speed up your Web applications with HTML5 WebSockets
PDF
servlets
PPT
Network
PPTX
Spicy javascript: Create your first Chrome extension for web analytics QA
DOCX
Laporan tugas network programming
DOCX
Chatting dengan beberapa pc laptop
PDF
About Node.js
PDF
Creating a Whatsapp Clone - Part II - Transcript.pdf
DOCX
I need you to modify and change the loop in this code without changing.docx
PPT
Networking Core Concept
PDF
Connecting to a Webservice.pdf
JavaExamples
Server1
201913046 wahyu septiansyah network programing
java sockets
香港六合彩 &raquo; SlideShare
Baocao Web Tech Java Mail
Networking and Data Access with Eqela
WebTalk - Implementing Web Services with a dedicated Java daemon
Creating a Whatsapp Clone - Part II.pdf
Speed up your Web applications with HTML5 WebSockets
servlets
Network
Spicy javascript: Create your first Chrome extension for web analytics QA
Laporan tugas network programming
Chatting dengan beberapa pc laptop
About Node.js
Creating a Whatsapp Clone - Part II - Transcript.pdf
I need you to modify and change the loop in this code without changing.docx
Networking Core Concept
Connecting to a Webservice.pdf
Ad

More from fashiongallery1 (20)

PDF
For this lab you will complete the class MyArrayList by implementing.pdf
PDF
Discuss the character and impact of the economic and legal revouluti.pdf
PDF
Discrete Math -Use induction to prove. The city of Inductionapolis.pdf
PDF
Describe polarization and why it is important to WLANs.Solution.pdf
PDF
Describe the four basic elements of most communication systems.So.pdf
PDF
Can someone please help me figure out how to do this Required Resou.pdf
PDF
Assume that the Current Assets for Shine Co. as of Decebmer 31, 2011.pdf
PDF
All computer are configured for TCPIP connectivity. This exercise i.pdf
PDF
4. At what temperature will a solution of 8.27 g CaCl2 in 45.0 g H2.pdf
PDF
Briefly Explain all these points belowA. Marketing channels VS cha.pdf
PDF
Write a class that implements the BagInterface. BagInterface should .pdf
PDF
write an equation for the transformation of the graph of y =f(x) tra.pdf
PDF
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
PDF
Why are helper T-cells called helper cellsThey help pathogens i.pdf
PDF
Which of the following is NOT true of the Sons of Liberty a. New Yor.pdf
PDF
What made the Later Roman Economy so unstable (Bennette, Medieval E.pdf
PDF
What data would illustrate whether these underlying problems are occ.pdf
PDF
1. What are distinct characteristics of baby boomers, generation X, .pdf
PDF
VERSION The cells denoted by the letter Ain the figure to.pdf
PDF
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdf
For this lab you will complete the class MyArrayList by implementing.pdf
Discuss the character and impact of the economic and legal revouluti.pdf
Discrete Math -Use induction to prove. The city of Inductionapolis.pdf
Describe polarization and why it is important to WLANs.Solution.pdf
Describe the four basic elements of most communication systems.So.pdf
Can someone please help me figure out how to do this Required Resou.pdf
Assume that the Current Assets for Shine Co. as of Decebmer 31, 2011.pdf
All computer are configured for TCPIP connectivity. This exercise i.pdf
4. At what temperature will a solution of 8.27 g CaCl2 in 45.0 g H2.pdf
Briefly Explain all these points belowA. Marketing channels VS cha.pdf
Write a class that implements the BagInterface. BagInterface should .pdf
write an equation for the transformation of the graph of y =f(x) tra.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Why are helper T-cells called helper cellsThey help pathogens i.pdf
Which of the following is NOT true of the Sons of Liberty a. New Yor.pdf
What made the Later Roman Economy so unstable (Bennette, Medieval E.pdf
What data would illustrate whether these underlying problems are occ.pdf
1. What are distinct characteristics of baby boomers, generation X, .pdf
VERSION The cells denoted by the letter Ain the figure to.pdf
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdf
Ad

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Computing-Curriculum for Schools in Ghana
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Classroom Observation Tools for Teachers
PDF
RMMM.pdf make it easy to upload and study
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Types and Its function , kingdom of life
PPTX
Lesson notes of climatology university.
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
Pharma ospi slides which help in ospi learning
Renaissance Architecture: A Journey from Faith to Humanism
Computing-Curriculum for Schools in Ghana
O7-L3 Supply Chain Operations - ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Final Presentation General Medicine 03-08-2024.pptx
Classroom Observation Tools for Teachers
RMMM.pdf make it easy to upload and study
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
VCE English Exam - Section C Student Revision Booklet
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Insiders guide to clinical Medicine.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Anesthesia in Laparoscopic Surgery in India
Sports Quiz easy sports quiz sports quiz
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Types and Its function , kingdom of life
Lesson notes of climatology university.
Module 4: Burden of Disease Tutorial Slides S2 2025

Hi, I need some one to help me with Design a client-server Chat so.pdf

  • 1. Hi, I need some one to help me with "Design a client-server Chat software using java or C, the software should have sign up new user,and sign in user, send text, send file, and join chat room" the more features the software has the better. tnx History u Messenge Serve server Database File 9/14/2012 9:01 PM XML Document 9/14/2012 10:33 AM Executable Jar File 9/14/2012 10:34 AM Executable Jar File Browse... Start Server 1 KB 48 KB Messenger Host Address localhost Username Anurag History File ssage File Host Port 13000 Password Connect Sign Up Show Send Message Solution Server Class import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.*; import java.util.zip.GZIPOutputStream; import javax.swing.SwingUtilities; public class Server extends JFrame implements ActionListener { public JList online; private JTextField ipaddress, textMessage; private JButton send, start, disconnect; private JTextArea chatArea; private JLabel port; int client[] = new int[100]; private ObjectOutputStream out[] = new ObjectOutputStream[client.length+ 1]; private ObjectInputStream in[] = new ObjectInputStream[client.length+ 1]; String username[] = new String[client.length+1]; static String b; public String nm, usm; private ServerSocket server; private Socket connect;
  • 2. boolean success = true; int id=0; ArrayList UserList = new ArrayList(); public Server() { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.setPreferredSize(new Dimension(650, 500)); JPanel p = new JPanel(); p.setLayout(new FlowLayout()); p.setBackground(Color.LIGHT_GRAY); p.add(port = new JLabel("Port No")); p.add(ipaddress = new JTextField("1500")); p.add(start = new JButton("START")); p.add(disconnect = new JButton("DISCONNECT")); disconnect.setEnabled(false); start.setBorderPainted(false); start.setBackground(Color.yellow); start.setForeground(Color.WHITE); disconnect.setBorderPainted(false); disconnect.setBackground(Color.yellow); disconnect.setForeground(Color.WHITE); ipaddress.setCaretPosition(0); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); p1.setBackground(Color.LIGHT_GRAY); p1.add(chatArea = new JTextArea()); chatArea.setPreferredSize(new Dimension(300, 350)); chatArea.setLineWrap(true); chatArea.setEditable(false); JPanel p2 = new JPanel(); p2.setLayout(new FlowLayout()); p2.setBackground(Color.LIGHT_GRAY); p2.add(textMessage = new JTextField(20)); p2.add(send = new JButton("SEND"));
  • 3. send.setBackground(Color.blue); send.setForeground(Color.WHITE); send.setBorderPainted(false); start.addActionListener(this); send.addActionListener(this); c.add(p, BorderLayout.NORTH); c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); } SimpleDateFormat log = new SimpleDateFormat("HH:mm"); String d = log.format(new Date()); public void Start() { int portNo = 0; try { String no = ipaddress.getText(); portNo = Integer.parseInt(no); chatArea.append("Connection to port " + portNo + "... "); server = new ServerSocket(portNo); success = true; } catch (Exception ex) { chatArea.append("Error cannot bind to port "); success = false; } if (success == true) { addClient ob1 = new addClient("RunServer"); start.setEnabled(false); disconnect.setEnabled(true); } } public class addClient implements Runnable { Thread t; addClient(String tot) { t = new Thread(this, tot); t.start();
  • 4. } public void run() { while (true) { try { try { WaitClient(); } catch (Exception ex) { break; } for (int i = 0; i < client.length; i++) { if (client[i] == 0) { client[i] = i + 1; id = i; break; } } out[client[id]] = new ObjectOutputStream(connect.getOutputStream()); out[client[id]].flush(); in[client[id]] = new ObjectInputStream(connect.getInputStream()); chatArea.append(d + " Client:[" + client[id] + "] : Connected successful "); sendUser(client[id], "Connected to the server"); ChatMessage cm = (ChatMessage) in[client[id]].readObject(); handle(client[id], cm); } catch (Exception e) { e.printStackTrace(); } } }
  • 5. } public synchronized void handle(int num, ChatMessage cm){ if(cm.type.equals("login")){ username[client[findClient(num)]] = cm.sender; send(client[findClient(num)], new ChatMessage("login", "SERVER", "TRUE", cm.sender)); Announce("newuser", "SERVER", cm.sender); SendUserList(cm.sender); }else if(cm.type.equals("message")){ if(cm.recipient.equals("All")){ Announce("message", cm.sender, cm.content); } else{ send(findUserThread(cm.recipient), new ChatMessage(cm.type, cm.sender, cm.content, cm.recipient)); send(client[findClient(num)], new ChatMessage(cm.type, cm.sender, cm.content, cm.recipient)); } } } public void SendUserList(String toWhom){ for(int i = 0; i < id; i++){ send(findUserThread(toWhom), new ChatMessage("newuser", "SERVER", username[client[i]], toWhom)); } } public int findUserThread(String usr){
  • 6. for(int i = 0; i < id; i++){ if(username[client[i]].equals(usr)){ return client[i]; } } return id; } private int findClient(int n){ for (int i = 0; i < id; i++){ if (client[i] == n){ return client[i]; } } return id; } private void WaitClient() throws IOException { chatArea.append(d + " : Waiting for connection... "); connect = server.accept(); chatArea.append(d + " : Now connected to " + connect.getInetAddress().getHostName() + " "); } //send message to specific user public void send(int number, ChatMessage cm) { try { out[number].writeObject(cm); out[number].flush();
  • 7. } catch (Exception e) { } } public void sendUser(int number, String info) { try { out[number].writeObject(info); out[number].flush(); } catch (Exception e) { } } public void Announce(String type, String sender, String content){ ChatMessage cm = new ChatMessage(type, sender, content, "All"); for(int i = 0; i < id; i++){ send(client[i], cm); } } public void actionPerformed(ActionEvent e) { if (e.getSource() == send) { } else if (e.getSource() == start) { Start(); } if (e.getSource() == disconnect) { } } } Main class import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.io.BufferedOutputStream;
  • 8. import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class Main extends javax.swing.JFrame { private ObjectOutputStream out; private ObjectInputStream in; static String b; //variable for message private Socket join; boolean success = true; private String serverIP = "10.1.1.1"; ArrayList userlist = new ArrayList(); SimpleDateFormat log = new SimpleDateFormat("HH:mm"); String d = log.format(new Date()); public File file; public String serverAddr, username, password; DefaultListModel model = new DefaultListModel(); public Main() { initComponents(); } private void initComponents() { jButton3 = new javax.swing.JButton(); start = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); textMessage = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); chatArea = new javax.swing.JTextArea(); usernm = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel();
  • 9. send = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); online = new javax.swing.JList(); upload = new javax.swing.JButton(); filename = new javax.swing.JTextField(); stop = new javax.swing.JButton(); login = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); ip = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); portnumber = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); passwordfield = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("ICARE "); setFocusable(false); setPreferredSize(new java.awt.Dimension(840, 650)); setResizable(false); getContentPane().setLayout(null); jButton3.setText("Send"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(710, 110, 100, 30); start.setBackground(new java.awt.Color(51, 51, 255)); start.setFont(new java.awt.Font("Tahoma", 0, 14)); start.setForeground(new java.awt.Color(255, 255, 255)); start.setText("Start"); start.setBorder(null); start.setBorderPainted(false); start.setRequestFocusEnabled(false); start.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {
  • 10. startActionPerformed(evt); } }); getContentPane().add(start); start.setBounds(20, 100, 90, 40); getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 820, 0); getContentPane().add(textMessage); textMessage.setBounds(270, 450, 440, 70); chatArea.setColumns(20); chatArea.setFont(new java.awt.Font("Arial", 0, 14)); chatArea.setRows(5); jScrollPane2.setViewportView(chatArea); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(270, 150, 540, 290); getContentPane().add(usernm); usernm.setBounds(540, 10, 170, 30); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel1.setText("Enter your nickname :"); getContentPane().add(jLabel1); jLabel1.setBounds(380, 10, 160, 30); send.setBackground(new java.awt.Color(51, 51, 255)); send.setFont(new java.awt.Font("Tahoma", 0, 14)); send.setForeground(new java.awt.Color(255, 255, 255)); send.setText("Send"); send.setBorder(null); send.setBorderPainted(false); send.setRequestFocusEnabled(false); send.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sendActionPerformed(evt); } }); getContentPane().add(send); send.setBounds(720, 470, 90, 40); online.setBackground(new java.awt.Color(0, 0, 0));
  • 11. online.setFont(new java.awt.Font("Tahoma", 0, 12)); online.setForeground(new java.awt.Color(102, 255, 0)); jScrollPane3.setViewportView(online); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(20, 150, 230, 370); upload.setFont(new java.awt.Font("Tahoma", 0, 18)); upload.setText("+"); upload.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadActionPerformed(evt); } }); getContentPane().add(upload); upload.setBounds(650, 110, 50, 30); getContentPane().add(filename); filename.setBounds(270, 110, 370, 30); stop.setBackground(new java.awt.Color(51, 51, 255)); stop.setFont(new java.awt.Font("Tahoma", 0, 14)); stop.setForeground(new java.awt.Color(255, 255, 255)); stop.setText("Log Out"); stop.setToolTipText(""); stop.setBorder(null); stop.setBorderPainted(false); stop.setRequestFocusEnabled(false); stop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopActionPerformed(evt); } }); getContentPane().add(stop); stop.setBounds(720, 60, 90, 40); login.setBackground(new java.awt.Color(51, 51, 255)); login.setFont(new java.awt.Font("Tahoma", 0, 14)); login.setForeground(new java.awt.Color(255, 255, 255)); login.setText("Log In"); login.setToolTipText("");
  • 12. login.setBorder(null); login.setBorderPainted(false); login.setRequestFocusEnabled(false); login.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loginActionPerformed(evt); } }); getContentPane().add(login); login.setBounds(720, 10, 90, 40); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel3.setText("Port No :"); jLabel3.setToolTipText(""); getContentPane().add(jLabel3); jLabel3.setBounds(20, 60, 100, 30); getContentPane().add(ip); ip.setBounds(110, 20, 150, 30); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel4.setText("IP Address :"); jLabel4.setToolTipText(""); getContentPane().add(jLabel4); jLabel4.setBounds(20, 20, 100, 30); getContentPane().add(portnumber); portnumber.setBounds(110, 60, 150, 30); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel5.setText("Enter your password :"); getContentPane().add(jLabel5); jLabel5.setBounds(380, 60, 160, 30); getContentPane().add(passwordfield); passwordfield.setBounds(540, 60, 170, 30); pack(); } private void startActionPerformed(java.awt.event.ActionEvent evt) { Start(); String group = "All"; online.setModel(model);
  • 13. model.addElement(group); online.setSelectedIndex(0); send(new ChatMessage("test", "testUser", "testContent", "SERVER")); } private void sendActionPerformed(java.awt.event.ActionEvent evt) { String z = textMessage.getText(); String target = online.getSelectedValue().toString(); if(!z.isEmpty() && !target.isEmpty()){ textMessage.setText(""); send(new ChatMessage("message", username, z, target)); } } private void uploadActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); fileChooser.showDialog(this, "Select File"); file = fileChooser.getSelectedFile(); if (file != null) { if (!file.getName().isEmpty()) { String str; if (filename.getText().length() > 30) { String t = file.getPath(); str = t.substring(0, 20) + " [...] " + t.substring(t.length() - 20, t.length()); } else { str = file.getPath(); } filename.setText(str); } } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
  • 14. long size = file.length(); if (size < 120 * 1024 * 1024) { send(new ChatMessage("upload_req", username, file.getName(), online.getSelectedValue().toString())); } else { chatArea.append("File is size too large "); } } private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN- FIRST:event_stopActionPerformed // if (!username.isEmpty()) { send(new ChatMessage("logout", username, password, "SERVER")); } } private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN- FIRST:event_loginActionPerformed username = usernm.getText(); password = passwordfield.getText(); if(!username.isEmpty() && !password.isEmpty()){ send(new ChatMessage("login", username, password, "SERVER")); } } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } }
  • 15. } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVE RE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Main().setVisible(true); } }); } public javax.swing.JTextArea chatArea; public javax.swing.JTextField filename; public javax.swing.JTextField ip; public javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; public javax.swing.JButton login;
  • 16. public javax.swing.JList online; public javax.swing.JPasswordField passwordfield; public javax.swing.JTextField portnumber; public javax.swing.JButton send; public javax.swing.JButton start; public javax.swing.JButton stop; private javax.swing.JTextField textMessage; public javax.swing.JButton upload; public javax.swing.JTextField usernm; public void Start() { try { start.setEnabled(false); chatArea.append(d + " : Attempting connection... "); join = new Socket(serverAddr, 10500); chatArea.append(d + " : Connected to - " + join.getInetAddress().getHostName() + " "); success = true; } catch (Exception ex) { chatArea.append("Error cannot bind to port "); success = false; } if (success == true) { ClientThread ct = new ClientThread(); } } class ClientThread implements Runnable { ClientThread ct; Thread t;
  • 17. ClientThread() { t = new Thread(this, "RunClient"); t.start(); } public void run() { try { try { out = new ObjectOutputStream(join.getOutputStream()); out.flush(); in = new ObjectInputStream(join.getInputStream()); b = (String) in.readObject(); chatArea.append(b + " "); chatArea.setCaretPosition(chatArea.getText().length()); } catch (Exception e) { } CThread c1 = new CThread(); } catch (Exception ex) { } } } class CThread implements Runnable { CThread ob1; Thread t; CThread() { t = new Thread(this, "Message"); t.start(); } public void run() { try { do { try { ChatMessage cm = (ChatMessage) in.readObject(); System.out.println("Incoming : "+cm.toString()); if(cm.type.equals("login")){ if(cm.content.equals("TRUE")){ chatArea.append("[SERVER > Me] : Login Successful ");
  • 18. } else{ chatArea.append("[SERVER > Me] : Login Failed "); } } else if(cm.type.equals("test")){ start.setEnabled(false); }else if(cm.type.equals("message")){ if(cm.recipient.equals(username)){ chatArea.append("["+cm.sender +" > Me] : " + cm.content + " "); } else{ chatArea.append("["+ cm.sender +" > "+ cm.recipient +"] : " + cm.content + " "); } }else if(cm.type.equals("newuser")){ online.setModel(model); model.addElement(cm.content); }else if(cm.type.equals("upload_req")){ JFileChooser jf = new JFileChooser(); jf.setSelectedFile(new File(cm.content)); int returnVal = jf.showSaveDialog(this); String saveTo = jf.getSelectedFile().getPath(); if(saveTo != null && returnVal == JFileChooser.APPROVE_OPTION){ Download dwn = new Download(saveTo); Thread t = new Thread(dwn); t.start(); send(new ChatMessage("upload_res", username, (""+dwn.port), cm.sender)); } else{ send(new ChatMessage("upload_res", username, "NO", cm.sender)); }
  • 19. } else if(cm.type.equals("upload_res")){ if(!cm.content.equals("NO")){ int port = Integer.parseInt(cm.content); String addr = cm.sender; Upload upl = new Upload(serverAddr, port, file); Thread t = new Thread(upl); t.start(); } else{ chatArea.append("[SERVER > Me] : "+cm.sender+" rejected file request "); } } else{ chatArea.append("[SERVER > Me] : Unknown message type "); } } catch (Exception ex) { chatArea.append("Server is disconnected" + " "); try { in.close(); out.close(); join.close(); } catch (Exception ex2) { } } } while (!b.equalsIgnoreCase("bye")); } catch (Exception ex) { } } } void send(ChatMessage cm) { try { out.writeObject(cm);
  • 20. out.flush(); } catch (Exception e) { } } } Chat class import java.io.Serializable; public class Chat implements Serializable{ private static final long serialVersionUID = 1L; public String type, sender, content, recipient; public Chat(String type, String sender, String content, String recipient){ this.type = type; this.sender = sender; this.content = content; this.recipient = recipient; } @Override public String toString(){ return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}"; } }