Results 1 to 6 of 6

Thread: Multi-threaded Java Server

  1. #1
    Join Date
    Aug 2005
    Posts
    293

    Multi-threaded Java Server

    Introduction

    Here we will try to explain the basic mechanisms of communication via sockets by building a java multiclient server. This server will work to simply redirect the flow arriving from a client connected to all others and this regardless of the type of client and System hosting it. Indeed sockets layer is a low enough level to be included in most systems and to be supported by a majority of programming languages.

    Here are the features of java server that we are going to create, called TestServer:

    - Server in Java, so multi-platform,
    - Multi-threaded, so with the ability to accept multiple clients simultaneously,
    - Action server: receives a message from the client, then sends to all other connected
    - Ability to query the server through server controls.

    All this may seem little, but it implies a universal server. In addition to being multiplatform, it will be very easy to relate to clients from different languages. Thus, it is possible to provide customers of all types of these (flash, java, c #, c + +, Delphi etc.). The drawback is security, since anyone can develop a client to "hinder" your application. But it does not make an IRC server, and TestServer may be suitable for small applications.

    The operations

    Here is an overview of the architecture of the application we are going to develop.



    General Definition of a Thread: This is a set of instructions that will share the processor with other "pieces" of the program. We have the impression that several actions are performed in parallel.

    Here we have three kinds of thread:

    - The main thread: it will wait for connections to the listening port opened to the server. At each connection it will start a new thread type customer.
    - The client thread: they are associated with each connected client, it is responsible to wait for a message. Each time, it will send the received message to all connected clients.
    - The thread of control: it waits for the tape server admin commands in the console to do something.

  2. #2
    Join Date
    Aug 2005
    Posts
    293

    Re: Multithreaded Java Server

    Development

    The language chosen here is the java, just because you can run the server as easily on Unix than Windows or Mac (and also because the sockets are quite easy to use java).

    We will create 3 classes:

    1. TestServer: Is the main thread

    Contains the following methods:
    - Public static void main (String args [])
    - Private static void printWel (Integer port)
    - Public synchronized void Sendall (String message, String str)
    - Public synchronized void delCli (int i)
    - Synchronized public int addCli (PrintWriter out)
    - Synchronized public int getNbCli ()

    2. TestThread: Corresponds to the client thread

    Contains the following methods:
    - TestThread (Socket s, TestServer ts)
    - Public void run ()

    3. Orders: Corresponds to the thread commands

    Contains the following methods:
    - Orders (TestServer ts)
    - Public void run ()

    Create a directory "Test" and place are three types of text files empty TestServer.java, TestThread.java, Commands.java. In the explanations we will not detail too much code, it seems sufficiently commented to understand every line.

  3. #3
    Join Date
    Aug 2005
    Posts
    293

    Re: Multithreaded Java Server

    The TestServer.java code

    Code:
    import java.net .*;
    import java.io. *;
    import java.util .*;
    
    / / ** Main class server, manages the overall information **
    Public class TestServer
    {
      private Vector vec = new Vector (); / / Will contain all the output stream to client
      private int ncli = 0; / / Total number of clients connected
    
      / / ** Method: the first method executed, it waits for connections **
      Public static void main (String args [])
      {
        TestServer ser = new TestServer (); / / Instance of main class
        try
       {
          Integer pt;
          if(args.length <= 0) pt =new Integer ("18000"); / / If no argument default pt 18000
          else pt = new Integer (args [0]); / / Otherwise it is the pt number passed as argument
    
          new Orders (ser); / / Starts the thread management commands
    
          ServerSocket ss = new ServerSocket (pt.intValue ()); / / Open a socket server on pt
          printWel (pt);
          while (true) / / Wait loop connection (blocking on ss.accept)
          {
            new TestThread (ss.accept () ser); / / Client connects, a new client thread is started
          }
        }
        catch (Exception e) ()
      }
    
      / / ** Method: Displays the greeting **
      static private void printWel (Integer pt)
      {
        System.out.println ("--------");
        System.out.println ("TestServer: the author");
        System.out.println ("Copyright: Example");
        System.out.println ("Last version: the date");
        System.out.println ("--------");
        System.out.println ("Start on pt:"pt.toString + ());
        System.out.println ("--------");
        System.out.println (Exit: type \ "quit \"");
        System.out.println ("Many online: type \"Total \"");
        System.out.println ("--------");
      }
    
    
      / / ** Method: Sends the message to all clients **
      synchronized Public void Sendall (String messageString slasti)
      {
        PrintWriter out; / / Declaration of a variable for sending text to the client
        for (int i = 0; i <vec.size (); i + +) / / Path of the table connected
       {
          out = (PrintWriter) vec.elementAt (i); / / Extract the current element (type PrintWriter)
          if (out! = null) / / Security element must not be empty
          {
              / / Write the text passed as parameter (and a string concatenation of string end if necessary)
            out.print (message + slasti);
            out.flush (); / / Send the output stream
          }
        }
      }
    
      / / ** Method: destroy the client no i **
      synchronized Public void delCli (int i)
      {
        ncli -; / / Client less! snif
        if (vec.elementAt (i)! = null) / / Element exists ...
       {      vec.removeElementAt (i); / / ... it removes
        }
      }
    
      / / ** Method: Adds a new client in the list **
      synchronized Public int addCli (PrintWriter out)
      {
        ncli + +; / / Client and more! 
        vec.addElement (out); / / Add the new output stream in Table
        return vec.size () -1; / / It returns the number of clients added (size-1)
      }
    
      / / ** Method: number of clients connected **
      synchronized Public int getNbClients ()
      {
        return ncli; / / Returns the number of clients connected
      }
    
    }
    The static function main () is executed first to launch the application. Parameters passed to start the application are stored in the array of strings args []. The only argument is that we manage the port number. If the argument is absent, then the port will be 18000. If the port is already taken by another application, or a problem occurs during the creation of ServerSoket, an exception is thrown and an error message is displayed. Just after the ServerSocket instantiation of a greeting is launched and the thread waiting for orders.

  4. #4
    Join Date
    Aug 2005
    Posts
    293

    Re: Multithreaded Java Server

    The TestThread.java code


    Code:
    import java.net .*;
    import java.io. *;
    
    class TestThread implements Runnable
    {
      private thr Thread; / / Will contain the client thread
      private Socket soc; / / Receive socket linking the customer
      private PrintWriter pw; / / For managing the output stream
      private BufferedReader buff; / / For managing the inflow
      private TestServer ser; / / To use methods of main class
      private int _numClient = 0; / / Will contain the number of customers managed by the thread
    
      / / ** Constructor: create the necessary dialogue with the customer **
      TestThread (Socket s, TestServer tser) / / The parameter s is given in TestServer by ss.accept ()
     {
        ser = tser; / / Transition from local comprehensive (for management in other methods)
        soc = s; / / Passing local global
        try
        {
          / / Making a variable to use the output stream with string
          pw = new PrintWriter (soc.getOutputStream ());
          / / Making a variable for the use of inflows with string
          buff = new BufferedReader (new InputStreamReader (soc.getInputStream ()));
          / / Add the output stream from the list and the number of recovery
          _numClient = tser.addCli (pw);
        }
        catch (IOException e) ()
    
        thr = new Thread (this); / / Instantiate the thread
        thr.start (); / / Start the thread, the function run () is launched here
      }
    
      / / ** Method: run to start the thread by t.start () **
      / / ** It waits for messages from the server and redirects **
      / / This method must necessarily be implemented because the interface Runnable
      Public void run ()
      {
        String message = ""; / / Declaration of the variable that will receive messages from client
        / / On the console shows the connection of a new customer
        System.out.println ("A new client has connected, no"_numClient +);
        try
        {
          / / Read the incoming data is done character by character ...
          / / ... to find a character string end
          char ch [] = new char[1]; / / Declaration of an array of char than 1 element, buff.read () to store the char read
          while(buff.read (ch, 0, 1)! =- 1) / / Loop waiting for messages from the client (blocking on buff.read ())
          {
              / / Look if we reach the end of a string ...
            if (ch [0]! = '\ u0000' & & ch [0]! = '\ n' & & ch [0]! = '\ r')
                    message + = ch [0]; / / ... if not, it concatenates the character in the message
            else if(! message.equalsIgnoreCase ("")) / / Just checking in principle
            {
              if(ch [0] == '\ u0000') / / The last character is '\ u0000' (null termination char)
                  / / We send the message saying it will concatenate '\ u0000' when sending to the client
                ser.sendAll (message""+ ch [0]);
              else ser.sendAll (message""); / / Otherwise we send the message to all
              message = ""; / / We empty the message string for it to be reused
            }
          }
        }
        catch (Exception e) ()
        finally / / Finally happen most often when the client disconnects
        {
          try
          {
              / / It tells the console client disconnects
            System.out.println ("Customer No."+ + _numClient"Disconnected");
            ser.delCli (_numClient); / / We remove the client from the list
            soc.close (); / / Close socket if it has not already been (because of the exception thrown above)
          }
          catch (IOException e) ()
        }
      }
    }
    The socket created by ss.accept () is received by a parameter, from _s, thus creating the buffer managing the inflow and outflow. The thread is then started (run () method). A waiting loop data takes place. Once a character arrives as input, it is concatenated to the string message. The message is sent a termination character of string is detected. If it is '\ u0000', that will be appended to the message when sending (sendall method ()). This is necessary mainly because of the Flash clients for which the received message must end with the zero terminal. Other types of customers are generally more tolerant. At least TestServer operate independently of the type of customers. Finally, after any event leading to the end of the loop, the block finally () will be executed properly to end the existence of the client thread.

  5. #5
    Join Date
    Aug 2005
    Posts
    293

    Re: Multithreaded Java Server

    The Commands.java code

    Code:
    import java.io. *;
    
    class Orders implements Runnable
    {
      TestServer ser; / / To use methods of main class
      BufferedReader buff; / / For managing the input stream (the console)
      String str =""; / / Contain the typed command
      thrd Thread; / / Will contain the thread
    
      / / ** Constructor: initialize variables required **
      Orders (TestServer tser)
     {
        ser = tser; / / Passing local global
        / / Input stream from the console will be run over almost a BufferedReader
        buff = new BufferedReader (new InputStreamReader (System.in));
        thrd = new Thread (this); / / Instantiate the thread
        thrd.start (); / / Start the thread, the function run () is launched here
      }
    
      / / ** Method: waits for commands in the console and performs the requested action **
      Public void run () / / This method must necessarily be implemented because the interface Runnable
      {
        try
        {
          / / If no command is typed, it does nothing (on blocking buff.readLine ())
          while ((str = buff.readLine ())!=null)
          {
            if (str.equalsIgnoreCase ("quit")) / / Command "quit" detected ...
              System.exit (0); / / ... we then close the server
            else if(str.equalsIgnoreCase ("total")) / / Command "total" detected ...
            {
              / / ... it displays the number of clients currently connected
              System.out.println ("Number of connected"ser.getnbCli + ());
              System.out.println ("--------");
            }
            else
            {
              / / If the command is not "total" or "quit", it informs the user and given assistance
              System.out.println ("This command is not supported");
              System.out.println ("Exit: \"quit \"");
              System.out.println ("Number of connected: \"Total \"");
              System.out.println ("--------");
            }
            System.out.flush (); / / It displays everything that is waiting in the flow
          }
        }
        catch (IOException e) ()
      }
    }
    This is not essential in the functioning of the server, but offers the opportunity to own administration even if minimal. The class is instantiated at server loading (main () method of TestServer). It creates a departure from the input buffer from the stream from the system (text typed into the console in general, in a DOS window under Windows Terminal or Unix / Linux). The main activity (in run ()) is to wait for instructions and execute them. The method readLine () here is more appropriate and simpler than the read () used in the client thread. Of course the method readLine () was not interesting in the client thread since the zero terminal should be managed.

  6. #6
    Join Date
    Aug 2005
    Posts
    293

    Re: Multithreaded Java Server

    Compilation/Results

    The code is written, it remains to compile our. We assume that the JDK version 1.6 or higher (updates) is installed on your machine. As there is little use of advanced packages in our code, it should not be too much problem on jdk below. Open a console (DOS, xterm, ... depending on your OS). Change to the directory "Test" and do "javac *. java". Normally, a message indicates that it uses an API deprecated. We will ignore this message so its appearance indicates that the compilation was successful. The .class files with the same names as the .Java must be appeared in the directory "Test". Otherwise make sure you have completed the tasks correctly. Best of Luck.

Similar Threads

  1. How to setup multi-user streaming server, web interfaced
    By Wafeeq in forum Networking & Security
    Replies: 8
    Last Post: 26-09-2010, 05:54 AM
  2. Visual Studio 2008 multi-Threaded DLL
    By Panchu in forum Windows Software
    Replies: 6
    Last Post: 25-09-2010, 10:00 AM
  3. Multi-threaded application uses only one core
    By KACY5 in forum Software Development
    Replies: 4
    Last Post: 10-11-2009, 07:10 PM
  4. Information on Single Threaded Apartments
    By Brendan18 in forum Software Development
    Replies: 3
    Last Post: 09-06-2009, 10:51 AM
  5. Problem with multi OS on single System (XP and Windows Server 2003)
    By ashishgoel123 in forum Operating Systems
    Replies: 2
    Last Post: 19-09-2008, 12:16 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,714,048,477.78656 seconds with 17 queries