0% found this document useful (0 votes)
53 views28 pages

Dok Cs

This document contains code for a Java chat application with client and server components. The server code establishes a socket connection and listens for incoming client connections, adding them to arrays to track connected clients and user names. It handles user authentication and message broadcasting. The client code connects to the server, receives and displays messages and online users, and allows sending messages back to all connected clients via the server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views28 pages

Dok Cs

This document contains code for a Java chat application with client and server components. The server code establishes a socket connection and listens for incoming client connections, adding them to arrays to track connected clients and user names. It handles user authentication and message broadcasting. The client code connects to the server, receives and displays messages and online users, and allows sending messages back to all connected clients via the server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Class server_mychat.

java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class server_MyChat


{
public static ArrayList<Socket> ConnectionArray = new
ArrayList<Socket>();
public static ArrayList<String> CurrentUser = new
ArrayList<String>();

public static void main(String[] args) throws IOException


{
try
{
final int PORT = 444;
ServerSocket SERVER = new ServerSocket(PORT);
System.out.println("waiting for client...");

while(true)
{
Socket SOCK = SERVER.accept();
ConnectionArray.add(SOCK);
System.out.println("Client connected from :
"+SOCK.getLocalAddress().getHostName());

AddUserName(SOCK);
server_return_MyChat CHAT = new
server_return_MyChat(SOCK);
Thread X = new Thread(CHAT);
X.start();
}
}
catch(Exception X)
{
System.out.print(X);
}
}

public static void AddUserName(Socket X) throws IOException


{
Scanner INPUT = new Scanner(X.getInputStream());
String UserName = INPUT.nextLine();

CurrentUser.add(UserName);
for(int i = 1; i <=
server_MyChat.ConnectionArray.size(); i++)
{
Socket TEMP_SOCK =
(Socket)server_MyChat.ConnectionArray.get(i-1);
PrintWriter OUT = new
PrintWriter(TEMP_SOCK.getOutputStream());
OUT.println("#?!"+CurrentUser);
OUT.flush();
}
}
}

server_return_mychat.java

import java.net.*;

import java.io.*;

import java.util.Scanner;

public class server_return_MyChat implements Runnable

Socket SOCK;

private Scanner INPUT;

private PrintWriter OUT;

String MESSAGE = "";

public server_return_MyChat(Socket X)

this.SOCK = X;

public void CheckConnection() throws IOException

if(!SOCK.isConnected())

for(int i=1; i<=server_MyChat.ConnectionArray.size(); i++)

{
if(server_MyChat.ConnectionArray.get(i) == SOCK)

server_MyChat.ConnectionArray.remove(i);

for(int i=1; i<=server_MyChat.ConnectionArray.size(); i++)

Socket TEMP_SOCK = (Socket) server_MyChat.ConnectionArray.get(i-1);

PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());

TEMP_OUT.println(TEMP_SOCK.getLocalAddress().getHostName()+" disconnected...");

TEMP_OUT.flush();

System.out.println(TEMP_SOCK.getLocalAddress().getHostName()+" disconnected...");

public void run()

try

try

INPUT = new Scanner(SOCK.getInputStream());

OUT = new PrintWriter(SOCK.getOutputStream());

while(true)

CheckConnection();

if(!INPUT.hasNext())
{

return;

MESSAGE = INPUT.nextLine();

System.out.println("Client said : "+MESSAGE);

for(int i=1; i<=server_MyChat.ConnectionArray.size(); i++)

Socket TEMP_SOCK = (Socket) server_MyChat.ConnectionArray.get(i-1);

PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());

TEMP_OUT.println(MESSAGE);

TEMP_OUT.flush();

System.out.println("send to : "+TEMP_SOCK.getLocalAddress().getHostName());

finally

SOCK.close();

catch(Exception X)

System.out.println(X);

}
client_mychat.java

import java.io.IOException;

import java.io.PrintWriter;

import java.net.Socket;

import java.util.Scanner;

import javax.swing.JOptionPane;

public class client_MyChat implements Runnable

Socket SOCK;

Scanner INPUT;

Scanner SEND = new Scanner(System.in);

PrintWriter OUT;

public client_MyChat(Socket X)

this.SOCK = X;

public void run()

try

try

INPUT = new Scanner(SOCK.getInputStream());

OUT = new PrintWriter(SOCK.getOutputStream());

OUT.flush();

CheckStream();
}

finally

SOCK.close();

catch(Exception X)

System.out.print(X);

public void DISCONNECT() throws IOException

OUT.println(client_GUI_MyChat.UserName+" has disconnected");

OUT.flush();

SOCK.close();

JOptionPane.showMessageDialog(null, "You disconnected");

System.exit(0);

public void CheckStream()

while(true)

RECEIVE();

}
public void RECEIVE()

if(INPUT.hasNext())

String MESSAGE = INPUT.nextLine();

if(MESSAGE.contains("#?!"))

String TEMP1 = MESSAGE.substring(3);

TEMP1 = MESSAGE.replace("[", "");

TEMP1 = MESSAGE.replace("]", "");

String[] CurrentUser = TEMP1.split(", ");

client_GUI_MyChat.JL_ONLINE.setListData(CurrentUser);

else

client_GUI_MyChat.TA_CONVERSATION.append(MESSAGE+"\n");

public void SEND(String X)

OUT.println(client_GUI_MyChat.UserName+" : "+X);

OUT.flush();

client_GUI_MyChat.TF_MESSAGE.setText("");

}
client_gui_mychat.java

import java.awt.Dimension;

import java.awt.event.ActionEvent;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.*;

import java.net.*;

import java.io.PrintWriter;

import java.awt.Dimension;

import java.awt.TextField;

import java.awt.Toolkit;

public class client_GUI_MyChat extends javax.swing.JFrame

private static client_MyChat ChatClient;

public static String UserName = "chopper";

public client_GUI_MyChat() {

initComponents();

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Dimension frameSize = getSize();

setLocation((screenSize.width - frameSize.width)/2, (screenSize.height - frameSize.height)/2);

}
/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

B_CONNECT = new javax.swing.JButton();

jLabel8 = new javax.swing.JLabel();

teksutkIP = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

B_DISCONNECT = new javax.swing.JButton();

jLabel5 = new javax.swing.JLabel();

jScrollPane1 = new javax.swing.JScrollPane();

TA_CONVERSATION = new javax.swing.JTextArea();

jLabel6 = new javax.swing.JLabel();

jScrollPane2 = new javax.swing.JScrollPane();

JL_ONLINE = new javax.swing.JList();

jLabel7 = new javax.swing.JLabel();

TF_MESSAGE = new javax.swing.JTextField();

B_SEND = new javax.swing.JButton();

L_LoggedInAs = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 153));

jLabel1.setFont(new java.awt.Font("Miss Smarty Pants", 1, 36)); // NOI18N

jLabel1.setText("My Chat");

B_CONNECT.setText("Connect");

B_CONNECT.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

B_CONNECTActionPerformed(evt);

});

jLabel8.setText("IP Address :");

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addContainerGap()

.addComponent(jLabel1)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(B_CONNECT))

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(59, 59, 59)

.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(teksutkIP, javax.swing.GroupLayout.DEFAULT_SIZE, 112,


Short.MAX_VALUE)))

.addContainerGap())

);

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addContainerGap()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel8)

.addComponent(teksutkIP, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(B_CONNECT)

.addGap(0, 11, Short.MAX_VALUE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel1)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))

);

jLabel4.setText("Logged in as");

B_DISCONNECT.setText("Disconnect");

B_DISCONNECT.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

B_DISCONNECTActionPerformed(evt);
}

});

jLabel5.setText("Conversation");

TA_CONVERSATION.setColumns(20);

TA_CONVERSATION.setRows(5);

jScrollPane1.setViewportView(TA_CONVERSATION);

jLabel6.setText("User Online");

jScrollPane2.setViewportView(JL_ONLINE);

jLabel7.setText("Message");

B_SEND.setText("Send");

B_SEND.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

B_SENDActionPerformed(evt);

});

L_LoggedInAs.setBorder(javax.swing.BorderFactory.createEtchedBorder());

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()
.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel5)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jLabel6))

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,
false)

.addComponent(TF_MESSAGE)

.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

.addGap(42, 42, 42)

.addComponent(jLabel4)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(L_LoggedInAs, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0,
Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

.addComponent(B_DISCONNECT)

.addGap(0, 0, Short.MAX_VALUE))

.addComponent(B_SEND, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))

.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)

.addGap(0, 0, Short.MAX_VALUE)))

.addContainerGap())

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(L_LoggedInAs, javax.swing.GroupLayout.PREFERRED_SIZE, 25,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel4)))

.addComponent(B_DISCONNECT, javax.swing.GroupLayout.Alignment.TRAILING))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel5)

.addComponent(jLabel6))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(jScrollPane1)

.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 178,


Short.MAX_VALUE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jLabel7)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(B_SEND, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)

.addComponent(TF_MESSAGE))

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

private void B_DISCONNECTActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

try

ChatClient.DISCONNECT();

catch(Exception Y)

Y.printStackTrace();

private void B_CONNECTActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

BuildLogInWindows();

private void B_SENDActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

if(!TF_MESSAGE.getText().equals(""))
{

ChatClient.SEND(TF_MESSAGE.getText());

TF_MESSAGE.requestFocus();

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

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(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

} catch (InstantiationException ex) {


java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

//</editor-fold>

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(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(client_GUI_MyChat.class.getName()).log(java.util.logging.Level.SEVER
E, null, ex);

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new client_GUI_MyChat().setVisible(true);

});

public void Connect()

try

final int PORT = 444;

final String HOST = teksutkIP.getText();

Socket SOCK = new Socket(HOST, PORT);

System.out.println("You Connected to : "+HOST);

ChatClient = new client_MyChat(SOCK);

PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());

OUT.println(UserName);

OUT.flush();
Thread X = new Thread(ChatClient);

X.start();

catch(Exception X)

System.out.println(X);

JOptionPane.showMessageDialog(null,"server not responding.");

System.exit(0);

//---------------------------------------------------------

public void BuildLogInWindows()

LogInWindows.setTitle("What's your name");

LogInWindows.setSize(400,100);

LogInWindows.setResizable(false);

P_LogIn = new JPanel();

P_LogIn.add(L_EnterUserName);

P_LogIn.add(TF_UserNameBox);

P_LogIn.add(B_Enter);

LogInWindows.add(P_LogIn);

Dimension screenSizeL = Toolkit.getDefaultToolkit().getScreenSize();

Dimension frameSizeL = LogInWindows.getSize();

LogInWindows.setLocation((screenSizeL.width - frameSizeL.width)/2, (screenSizeL.height -


frameSizeL.height)/2);

Login_Action();

LogInWindows.setVisible(true);
}

public void Login_Action()

B_Enter.addActionListener(

new java.awt.event.ActionListener()

@Override

public void actionPerformed(java.awt.event.ActionEvent evt)

ACTION_B_ENTER();

);

public void ACTION_B_ENTER()

if(!TF_UserNameBox.getText().equals(""))

UserName = TF_UserNameBox.getText().trim();

L_LoggedInAs.setText(UserName);

server_MyChat.CurrentUser.add(UserName);

LogInWindows.setVisible(false);

B_SEND.setEnabled(true);

B_DISCONNECT.setEnabled(true);

B_CONNECT.setEnabled(false);

Connect();

}
else

JOptionPane.showMessageDialog(null, "Please enter your name.");

public static JFrame LogInWindows = new JFrame();

public static JTextField TF_UserNameBox = new JTextField(20);

private static JButton B_Enter = new JButton("Enter");

private static JLabel L_EnterUserName = new JLabel("Enter username : ");

private static JPanel P_LogIn = new JPanel();

// Variables declaration - do not modify

private javax.swing.JButton B_CONNECT;

private javax.swing.JButton B_DISCONNECT;

private javax.swing.JButton B_SEND;

public static javax.swing.JList JL_ONLINE;

private javax.swing.JLabel L_LoggedInAs;

public static javax.swing.JTextArea TA_CONVERSATION;

public static javax.swing.JTextField TF_MESSAGE;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JLabel jLabel6;

private javax.swing.JLabel jLabel7;

private javax.swing.JLabel jLabel8;

private javax.swing.JPanel jPanel1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JScrollPane jScrollPane2;


public static javax.swing.JTextField teksutkIP;

// End of variables declaration

You might also like