Question
Java In the server define an ArrayList to save all the clients that have made a connection and remove a client from the list once
Java
In the server define an ArrayList to save all the clients that have made a connection and remove a client from the list once they disconnect
package server1;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException;
public class Server1Frame extends javax.swing.JFrame {
/** * Creates new form Server1Frame */ public Server1Frame() { initComponents(); }
/** * 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") //
jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jbtnStartServer = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1);
jbtnStartServer.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jbtnStartServer.setText("Start Server"); jbtnStartServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnStartServerActionPerformed(evt); } });
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jbtnStartServer, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(70, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jbtnStartServer) .addContainerGap(71, Short.MAX_VALUE)) );
pack(); }//
private void jbtnStartServerActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //put all the server code in a thread //to avoid locking the UI Thread serverThread = new SimpleServerThread(); serverThread.start(); }
/** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //
/* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Server1Frame().setVisible(true); } }); } //=====================server thread======== private class SimpleServerThread extends Thread{ //you may define a custom constructor if you /eed to pass data to a thread, otherwise the //compiler will issue a default constructor @Override public void run() { ServerSocket server = null;
try{ server = new ServerSocket(9999); }catch(IOException ioe){ jTextArea1.setText("IOException:...... "+ ioe.getMessage()); return; } String hostAddress=""; String hostName=""; try { InetAddress hostInetAddress = InetAddress.getLocalHost(); hostAddress = hostInetAddress.getHostAddress(); hostName = hostInetAddress.getHostName(); }catch (UnknownHostException ex){ } jTextArea1.setText( "Server is ready: " + hostName+ " "+ hostAddress+":"+ "9999"); while(true){ try{ //get the client making a request Socket client = server.accept(); //display/log client info SocketAddress clientAddress = client.getRemoteSocketAddress(); jTextArea1.append(" Client socket address: "+ clientAddress); //start the client thread Thread thread = new ClientThread(client); thread.start(); }catch(IOException ioe){ }
}//end of while }//end of run
private void setVisible(boolean b) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }//end of class: serverthread //thread to deal with client private class ClientThread extends Thread{ private Socket client; public ClientThread(Socket client){ this.client = client; }
@Override public void run() { PrintWriter out = null; //for the server to send //a resonse BufferedReader in = null; //for the server //to read client request try { out = new PrintWriter(client.getOutputStream(),true); in = new BufferedReader( new InputStreamReader(client.getInputStream())); //get client request String request= ""; String response=""; String command; do{ request = in.readLine(); //Assuming that request contains protocol commands: String[] tokens = request.split(""); if(tokens.length >= 1) command = tokens[0]; else command= "default";//any value is ok to send the switch to //default switch(command){ case "add": if(tokens.length==3){ try{ double x = Double.parseDouble(tokens[1].trim()); double y = Double.parseDouble(tokens[2].trim()); double total = x+y; response = x+" + "+y+" = "+ total; } catch(NumberFormatException nfe) { response="add command requires 2 values"; } } else response="add command requires 2 values"; break; case "bye": response ="Good night: you have been disconnected. Come backat a later time"; break; case "error": response="request not in the right format"; break; default: response = "Undefined command request"; break; } //send response back out.println(response); }while(!request.equals("bye")); //close if(in != null)in.close(); if(out != null)out.close(); }catch (IOException ex){ } }//end of run } // Variables declaration - do not modify private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JButton jbtnStartServer; // End of variables declaration }
Start Server Display all Clients Start Server Display all ClientsStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered 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