client number in a java multithread server

I use two classes in my server

Myserver.java
private ExecutorService executorService = Executors.newFixedThreadPool(10);        

public static void main(String[] args) throws IOException {
  server = new MyServer();
  server.runServer();
}

private void runServer() {        
  int serverPort = 8071;
  try {
    System.out.println("Starting Server");
    serverSocket = new ServerSocket(serverPort); 

    while(true) {
      System.out.println("Waiting for request");
      try {
        Socket s = serverSocket.accept();
        System.out.println("Processing request");
        executorService.submit(new ServiceRequest(s));
      } catch(IOException ioe) {
        System.out.println("Error accepting connection");
        ioe.printStackTrace();
      }
    }
  }catch(IOException e) {
    System.out.println("Error starting Server on "+serverPort);
    e.printStackTrace();
  }
}

and

ServiceRequest.java
private Socket socket;
BufferedReader input = null;

public ServiceRequest(Socket connection) {
  this.socket = connection;
}

public void run() {

  try {
    //input = new BufferedReader(new InputStreamReader(socket.getInputStream()));


    DataInputStream din = new DataInputStream(socket.getInputStream());

    System.out.println("Client "+ clientID +"Connected");

I want to get the number of each Client in run() ( I want to get a result in the last line of the code ). How would I do this?

Answers


When you create a new service request, you can keep a global counter for IDs... but it's very important to use AtomicLong, not a regular int or long, if you want to keep unique ids.

private static AtomicLong idCounter = new AtomicLong();
private long clientId = idCounter.incrementAndGet();

This is how you can create clientIds in a threadsafe way, as the instance variable clientId will create a new value atomically each time a ServiceRequest is generated.


Need Your Help

How to sort an array of UTF-8 strings?

php arrays sorting utf-8

I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.