Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello ,
I created simple command line multithread application it work , but i faced a simple problem which is when 2 or 3 threads connect to server the server need to write to console equals to number of clients connected to my server example 2 clients connected , i need to write for example hi,BYE , hi goes to clients 1 and BYE goes to client2 . i didn't like this way so i need help by putting clientCode as key to define my client and send the message to it the following code will explain the functionality of clientCode and more things
here is Server code:
Java
package Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

// TODO: Auto-generated Javadoc
/**
 * The Class Server.
 */
public class Server {

	/** The reader. */
	BufferedReader reader;

	/** The data. */
	String data;

	/** The port. */
	private int port = 7898;

	/** The server socket. */
	private ServerSocket serverSocket;

	/** The socket. */
	private Socket socket;

	/** The input data. */
	String inputData;

	/** The map. */
	HashMap<Integer, Socket> map = new HashMap<Integer, Socket>();

	/** The writer. */
	PrintWriter writer;

	/** The client code. */
	int clientCode = 0;

	/**
	 * Instantiates a new server.
	 * 
	 * @param sa
	 *            the sa
	 */
	public Server(String sa) {

	}

	/**
	 * Instantiates a new server.
	 * @throws InterruptedException 
	 */
	public Server() throws InterruptedException {
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("waiting For connection on this port " + " "
					+ port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while (true) {
			try {
				socket = serverSocket.accept();

				Thread thread = new Thread(new ServerManager(socket));
				thread.start();
				thread.sleep(1000L);
			} catch (IOException e) {

				e.printStackTrace();
			}

		}
	}

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the arguments
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws InterruptedException
	 *             the interrupted exception
	 */
	public static void main(String[] args) throws IOException,
			ClassNotFoundException, InterruptedException {
		Server server = new Server();

		// server.invokingMethod();

	}

}


and here serverManager which most of server goes here:
Java
package Server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Random;

// TODO: Auto-generated Javadoc
/**
 * The Class ServerManager.
 */
class ServerManager implements Runnable {

	/** The socket. */
	Socket socket = null;

	/** The map. */
	HashMap<Integer, Socket> map = new HashMap<Integer, Socket>();

	/** The input stream. */
	BufferedReader inputStream;

	/** The input. */
	BufferedReader input;

	/** The output stream. */
	BufferedWriter outputStream;

	/** The buffered writer. */
	BufferedWriter bufferedWriter;

	/** The data. */
	String data;

	/** The input data. */
	String inputData;

	/** The client code. */
	int clientCode = 0;

	/**
	 * Instantiates a new server manager.
	 * 
	 * @param clientSocket
	 *            the client socket
	 */
	public ServerManager(Socket clientSocket) {
		this.socket = clientSocket;
		Random random = new Random();
		clientCode = Math.abs(random.nextInt());
	}

	/**
	 * Instantiates a new server manager.
	 */
	public ServerManager() {

	}

	/**
	 * The Class ServerReader.
	 */
	class ServerReader implements Runnable {

		/** The input stream. */
		InputStream inputStream;

		/**
		 * Instantiates a new server reader.
		 * 
		 * @param inputStream
		 *            the input stream
		 */
		public ServerReader(InputStream inputStream) {
			this.inputStream = inputStream;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {

			// When started keep seeking for socket input data
			while (true) {
				try {
					if (inputStream.available() > 0) {
						byte[] readData = new byte[inputStream.available()];
						System.out.println();
						inputStream.read(readData);
						System.out.println("Data from Client " + clientCode
								+ ": " + new String(readData));

					}
					Thread.sleep(1000L);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {

		try {
			System.out.println("The Client with Code " + clientCode + ": "
					+ "Connected");

			Thread thread = new Thread(
					new ServerReader(socket.getInputStream()));

			thread.start();
			outputStream = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			add(clientCode);

			data = dataFromConsole().toString();

			send(data);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Adds the.
	 * 
	 * @param clientCode
	 *            the client code
	 */
	public void add(Integer clientCode) {

		map.put(clientCode, socket);
	}

	/**
	 * Send.
	 * 
	 * @param message
	 *            the message
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws InterruptedException
	 *             the interrupted exception
	 */
	public void send(String message) throws IOException,
			ClassNotFoundException, InterruptedException {

		outputStream.write(message);
		outputStream.newLine();
		outputStream.flush();

	}

	/**
	 * Data from console.
	 * 
	 * @return the string
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public String dataFromConsole() throws IOException {
		input = new BufferedReader(new InputStreamReader(System.in));
		inputData = input.readLine();
		return inputData;
	}

	public void Disconnect() throws IOException {
		while (true) {

			input.close();
			outputStream.close();
			socket.close();
		}

	}
}

My client code built at the same way here expect the multithreading part.
Posted
Updated 20-Jan-12 3:50am
v2
Comments
Nagy Vilmos 20-Jan-12 9:51am    
If you paste in code please untick 'treat as plain text' next time.
hamzah1 20-Jan-12 9:55am    
i will next time .thanks

1 solution

You need to split up your code a bit, my suggestion would be:

ServerApp
Creates and starts a Server that manages all the connections.

Server
Runs on it's own thread and contains a single Listener that accepts inbound connections and a collection of Sessions for all of the connections.

Listener
Runs in it's own thread, creates a ServerSocket and creates a Session for each Socket that is given to the Server.

Session
Again runs on it's own thread.
Takes inbound messages from the client and forwards them to the Server.
Accepts outbound messages from the Server and forwards them to the client.

Each of the three server side components need to be thread safe, synchronize methods that can be called from two places.
I would manage everything by having a collection in the Server of all the sessions and then the Sessions themselves will keep the messages for processing and notify the server when they have something.

If you want more ideas, try searching for "multi threaded chat server" as that would probably give you a lot of the concepts you need to cover without being too complicated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900