Question
I have an application for tcp chat,with multi client in java, and i have code too but i need explaination in details about this code.
I have an application for tcp chat,with multi client in java, and i have code too but i need explaination in details about this code.
1.
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.util.Observable; import java.util.Observer;
// Class to manage Client chat Box. public class ChatClient {
/** Chat client access */ static class ChatAccess extends Observable { private Socket socket; private OutputStream outputStream;
@Override public void notifyObservers(Object arg) { super.setChanged(); super.notifyObservers(arg); }
/** Create socket, and receiving thread */ public void InitSocket(String server, int port) throws IOException { socket = new Socket(server, port); outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() { @Override public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); String line; while ((line = reader.readLine()) != null) notifyObservers(line); } catch (IOException ex) { notifyObservers(ex); } } }; receivingThread.start(); }
private static final String CRLF = " "; // newline
/** Send a line of text */ public void send(String text) { try { outputStream.write((text + CRLF).getBytes()); outputStream.flush(); } catch (IOException ex) { notifyObservers(ex); } }
/** Close the socket */ public void close() { try { socket.close(); } catch (IOException ex) { notifyObservers(ex); } } }
/** Chat client UI */ static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea; private JTextField inputTextField; private JButton sendButton; private ChatAccess chatAccess;
public ChatFrame(ChatAccess chatAccess) { this.chatAccess = chatAccess; chatAccess.addObserver(this); buildGUI(); }
/** Builds the user interface */ private void buildGUI() { textArea = new JTextArea(20, 50); textArea.setEditable(false); textArea.setLineWrap(true); add(new JScrollPane(textArea), BorderLayout.CENTER);
Box box = Box.createHorizontalBox(); add(box, BorderLayout.SOUTH); inputTextField = new JTextField(); sendButton = new JButton("Drgo"); box.add(inputTextField); box.add(sendButton);
// Action for the inputTextField and the goButton ActionListener sendListener = new ActionListener() { public void actionPerformed(ActionEvent e) { String str = inputTextField.getText(); if (str != null && str.trim().length() > 0) chatAccess.send(str); inputTextField.selectAll(); inputTextField.requestFocus(); inputTextField.setText(""); } }; inputTextField.addActionListener(sendListener); sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { chatAccess.close(); } }); }
/** Updates the UI depending on the Object argument */ public void update(Observable o, Object arg) { final Object finalArg = arg; SwingUtilities.invokeLater(new Runnable() { public void run() { textArea.append(finalArg.toString()); textArea.append(" "); } }); } }
public static void main(String[] args) { String server = args[0]; int port =2222; ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access); frame.setTitle("AplikacioniChat - lidhur me " + server + ":" + port); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true);
try { access.InitSocket(server,port); } catch (IOException ex) { System.out.println("Nuk mund t konektoht n " + server + ":" + port); ex.printStackTrace(); System.exit(0); } } }
2.
import javax.swing.*;
//Class to precise who is connected : Client or Server
public class ClientServer {
public static void main(String [] args){
Object[] selectioValues = { "Server","Klient"};
String initialSection = "Server";
Object selection = JOptionPane.showInputDialog(null, "Kyqu si : ", "MyChatApp", JOptionPane.QUESTION_MESSAGE, null, selectioValues, initialSection);
if(selection.equals("Server")){
String[] arguments = new String[] {};
new MultiThreadChatServerSync();
MultiThreadChatServerSync.main(arguments);
}else if(selection.equals("Klient")){
String IPServer = JOptionPane.showInputDialog("Jepni IP adresn e serverit:");
String[] arguments = new String[] {IPServer};
new ChatClient();
ChatClient.main(arguments);
}
}
}
3.
import java.io.DataInputStream; import java.io.IOException; import java.io.PrintStream; import java.net.Socket;
/** * * @author mohammed */
// For every client's connection we call this class public class clientThread extends Thread{ private String clientName = null; private DataInputStream is = null; private PrintStream os = null; private Socket clientSocket = null; private final clientThread[] threads; private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) { this.clientSocket = clientSocket; this.threads = threads; maxClientsCount = threads.length; }
@SuppressWarnings("deprecation") public void run() { int maxClientsCount = this.maxClientsCount; clientThread[] threads = this.threads;
try { /* * Create input and output streams for this client. */ is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); String name; while (true) { os.println("Jepni emrin tuaj."); name = is.readLine().trim(); if (name.indexOf('@') == -1) { break; } else { os.println("Emri nuk duhet t prmbaj karakterin '@'."); } }
/* Welcome the new the client. */ os.println("Mirsevini " + name + " n dhomn ton t biseds. Pr tu larguar shtypni/quit n nj rresht t ri."); synchronized (this) { for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] == this) { clientName = "@" + name; break; } } for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this) { threads[i].os.println("*** Nj prdorues i ri " + name + " hyri n dhomn e biseds !!! ***"); } } } /* Start the conversation. */ while (true) { String line = is.readLine(); if (line.startsWith("/quit")) { break; } /* If the message is private sent it to the given client. */ if (line.startsWith("@")) { String[] words = line.split("\\s", 2); if (words.length > 1 && words[1] != null) { words[1] = words[1].trim(); if (!words[1].isEmpty()) { synchronized (this) { for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this && threads[i].clientName != null && threads[i].clientName.equals(words[0])) { threads[i].os.println("<" + name + "> " + words[1]); /* * Echo this message to let the client know the private * message was sent. */ this.os.println(">" + name + "> " + words[1]); break; } } } } } } else { /* The message is public, broadcast it to all other clients. */ synchronized (this) { for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i].clientName != null) { threads[i].os.println("<" + name + "> " + line); } } } } } synchronized (this) { for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this && threads[i].clientName != null) { threads[i].os.println("*** Prdoruesi " + name + " po largohet nga dhoma e biseds !!! ***"); } } } os.println("*** Mirupafshim " + name + " ***");
/* * Clean up. Set the current thread variable to null so that a new client * could be accepted by the server. */ synchronized (this) { for (int i = 0; i < maxClientsCount; i++) { if (threads[i] == this) { threads[i] = null; } } } /* * Close the output stream, close the input stream, close the socket. */ is.close(); os.close(); clientSocket.close(); } catch (IOException e) { } } }
4.
import java.io.PrintStream; import java.io.IOException; import java.net.Socket; import java.net.ServerSocket; /** * * @author mohammed */
// the Server class public class MultiThreadChatServerSync { // The server socket. private static ServerSocket serverSocket = null; // The client socket. private static Socket clientSocket = null;
// This chat server can accept up to maxClientsCount clients' connections. private static final int maxClientsCount = 10; private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) {
// The default port number. int portNumber = 2222; if (args.length < 1) { System.out.println("Usage: java MultiThreadChatServerSync
/* * Open a server socket on the portNumber (default 2222). Note that we can * not choose a port less than 1023 if we are not privileged users (root). */ try { serverSocket = new ServerSocket(portNumber); } catch (IOException e) { System.out.println(e); }
/* * Create a client socket for each connection and pass it to a new client * thread. */ while (true) { try { clientSocket = serverSocket.accept(); int i = 0; for (i = 0; i < maxClientsCount; i++) { if (threads[i] == null) { (threads[i] = new clientThread(clientSocket, threads)).start(); break; } } if (i == maxClientsCount) { PrintStream os = new PrintStream(clientSocket.getOutputStream()); os.println("Serveri sht shum i zn. Provoni m von."); os.close(); clientSocket.close(); } } catch (IOException e) { System.out.println(e); } } } }
Please i need to explain me this question about my project:
1. Describe your algorithm design, showing what interactions happen between clients and the server.
Thanks
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started