Results 1 to 2 of 2
  1. #1
    gongshow20 is offline Member
    Join Date
    May 2013
    Posts
    6
    Rep Power
    0

    Default Using threads to handle multiple connections to server.

    I have a simple text chat server that I've been using to learn socket programming. It works now, I can start the server and have a client connect and disconnect just fine. I want to use threads to be able to handle multiple clients on the server but I have no idea how to implement this. Any pointers would be helpful.

    Here are the basic parts of my server class that relate to connections.
    The code in the wait for communication class that is commented out is my attempt at adding threads to handle connections.

    Java Code:
    public class Server extends JFrame {
    
    	private JTextField enterField;
    	private JTextArea displayArea;
    	private ObjectOutputStream output;
    	private ObjectInputStream input;
    	private ServerSocket server;
    	private Socket connection;
    	private int counter = 1;
    
    	public Server() {
    		super ("Server");
    		enterField = new JTextField();
    		enterField.setEditable(true);
    		enterField.addActionListener(new ActionListener() {
    
    			@Override
    			public void actionPerformed(ActionEvent event) {
    				sendData(event.getActionCommand());
    				enterField.setText("");
    
    			}
    		});
    		
    		add(enterField, BorderLayout.NORTH);
    		displayArea = new JTextArea();
    		add (new JScrollPane(displayArea));
    		setSize(300,150);
    		setLocation(500,500);
    		setVisible(true);
    	}
    	public void runServer() {
    		try {
    			if(server == null){
    			server = new ServerSocket(50499, 100);
    			}
    			displayMessage("\n Listening on Port: " + server.getLocalPort() + "\n");
    			
    	
    			while (true) {
    				try {
    					waitForCommunication();
    					getStreams();
    					processConnection();
    				} catch (EOFException eofException) {
    					displayMessage("\n Server terminated connection ");
    				} finally {
    					closeConnection();
    					++counter;
    				}
    			}
    		} catch (IOException ioException) {
    			ioException.printStackTrace();
    		}
    	}
    
    	private void closeConnection() {
    		displayMessage("\nTerminating connection\n");
    		setTextFieldEditable(false);
    		try {
    			output.close();
    			input.close();
    			connection.close();
    		} catch (IOException ioException) {
    			ioException.printStackTrace();
    		}
    		runServer();
    	}
    	private void processConnection() throws IOException {
    		String message = "Connection Sucessful";
    		sendData(message);
    
    		setTextFieldEditable(true);
    
    		do {
    			try {
    				message = (String) input.readObject();
    				displayMessage("\n" + message);
    			} catch (ClassNotFoundException classNotFoundException) {
    				displayMessage("\nUnknown object type recieved");
    			}
    		} while (!message.endsWith(">>> TERMINATE"));
    	}
    	
    	private void getStreams() throws IOException {
    		output = new ObjectOutputStream(connection.getOutputStream());
    		output.flush();
    
    		input = new ObjectInputStream(connection.getInputStream());
    
    		displayMessage("\nGOt I/O stream \n");
    
    	}
    	private void waitForCommunication() throws IOException {
    		displayMessage("Waiting for cennection \n");
    //		Thread addConnection = new Thread(new Runnable(){
    //
    //			@Override
    //			public void run() {
    //				try {
    					connection = (server.accept());
    //				} catch (IOException e) {
    //					// TODO Auto-generated catch block
    //					e.printStackTrace();
    //				}
    //
    //			}
    //				
    //		});
    //		addConnection.start();
    	
    		displayMessage("Connection" + counter + " received from: "
    				+ connection.getInetAddress().getHostName());
    	}
    }

  2. #2
    gongshow20 is offline Member
    Join Date
    May 2013
    Posts
    6
    Rep Power
    0

    Default Re: Using threads to handle multiple connections to server.

    So I have tried some different way to implement threads to process multiple clients and here is my latest solution.
    In my main I create an instance of the Server then call Server.runServer(). The problem I'm experiencing is that when I start() the startServer Thread it will not start the Thread.


    Java Code:
    public class Server extends JFrame {
    
    	private JTextField enterField;
    	private JTextArea displayArea;
    	private ObjectOutputStream output;
    	private ObjectInputStream input;
    	
    	private ExecutorService executor = Executors.newCachedThreadPool();
    
    	private ServerSocket server;
    	private Socket connection;
    	private int counter = 1;
    
    	public Server() {
    		super("Server");
    		enterField = new JTextField();
    		enterField.setEditable(true);
    		enterField.addActionListener(new ActionListener() {
    
    			@Override
    			public void actionPerformed(ActionEvent event) {
    				sendData(event.getActionCommand());
    				enterField.setText("");
    
    			}
    		});
    
    		add(enterField, BorderLayout.NORTH);
    		displayArea = new JTextArea();
    		add(new JScrollPane(displayArea));
    		setSize(300, 150);
    		setLocation(500, 500);
    		setVisible(true);
    
    	}
    	
    	public void runServer(){
    
    		Thread startServer = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				try {
    					server = new ServerSocket(50499, 100);
    					for (;;) {
    						Socket nextClient = server.accept();
    						new ClientThread(nextClient).start();
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    
    			}
    
    		});
    		
    		startServer.start();
    	}
    
    
    	private void closeConnection() {
    		displayMessage("\nTerminating connection\n");
    		setTextFieldEditable(false);
    		try {
    			output.close();
    			input.close();
    			connection.close();
    		} catch (IOException ioException) {
    			ioException.printStackTrace();
    		}
    	}
    
    	private void displayMessage(final String string) {
    		SwingUtilities.invokeLater(new Runnable() {
    
    			@Override
    			public void run() {
    				displayArea.append(string);
    			}
    
    		});
    
    	}
    	private void setTextFieldEditable(final boolean editable) {
    		SwingUtilities.invokeLater(new Runnable() {
    
    			@Override
    			public void run() {
    				enterField.setEditable(editable);
    
    			}
    
    		});
    
    	}
    	private void sendData(String message) {
    		try {
    			output.writeObject("SERVER>>> " + message);
    			output.flush();
    			displayMessage("\nSERVER>>> " + message);
    		} catch (IOException ioException) {
    			displayArea.append("\nError Writing Object");
    		}
    	}
    	
    	private class ClientThread extends Thread {
    
    
    		public ClientThread(Socket socket) throws IOException {
    			connection = socket;
    
    			output = new ObjectOutputStream(socket.getOutputStream());
    			output.flush();
    			input = new ObjectInputStream(socket.getInputStream());
    			displayMessage("Got I/O Stream\n");
    			displayMessage("Waiting for cennection \n");
    			connection = (server.accept());
    			displayMessage("Connection" + counter + " received from: "
    					+ connection.getInetAddress().getHostName());
    			++counter;
    			String message = "Connection Sucessful";
    			sendData(message);
    
    			setTextFieldEditable(true);
    			do {
    				try {
    					message = (String) input.readObject();
    					displayMessage("\n" + message);
    				} catch (ClassNotFoundException classNotFoundException) {
    					displayMessage("\nUnknown object type recieved");
    				}
    			} while (!message.endsWith(">>> TERMINATE"));
    
    			closeConnection();
    
    		}
    
    	}
    }

Similar Threads

  1. Protect java server from telnet connections?
    By Lionlev in forum Advanced Java
    Replies: 8
    Last Post: 10-30-2012, 10:34 PM
  2. Replies: 1
    Last Post: 10-29-2012, 10:49 AM
  3. One process open multiple threads on multiple CPUs
    By kfcnhl in forum Threads and Synchronization
    Replies: 2
    Last Post: 12-12-2011, 09:27 AM
  4. Replies: 1
    Last Post: 10-26-2010, 12:21 AM
  5. Running multiple threads on multiple CPU cores?
    By Dosta in forum Threads and Synchronization
    Replies: 2
    Last Post: 09-19-2010, 04:48 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •