Multithread Server

I ran into a problem while creating a multithread chat program. When a new user connects to the server, a new thread is created for him. All users are able to connect and send a message to the server. But I'd like to relay that message to all threads. (or chatters connected). Does anyone know how can I go about this?

I posted something like that a few months ago in replies 21 and 28 of Program Hanging on a Thread. The server is a multithreaded traditional socket program that switches messages from 1 user to many others, the client is a simple swing based terminal. Its like a crude chat room.

Similar Messages

  • MultiThreaded Server and Client connections query.

    I have written a MultiThreaded Server to accept incoming client requests.
    Multiple clients can connnect to this server and have a conversation.
    I invoke the 'MultiServer' from the command line and then invoke 3 clients
    from the command line.('Client').
    c:> java MultiServer
    c:> java Client
    c:> java Client
    c:> java Client
    All the 3 clients now run in their own thread and send messages
    to the server.
    The problem I am facing is this:
    When client1 connects to the server and sends a message to the server (with the server responding)
    it works fine.Both Server and Client can exchange messages.
    When client2 connects to the server and sends a message and when the server
    responds with a message,the message does NOT go to client2,but goes to Client1
    As Clients have their own thread to run,shouldnt the messages also be delivered to
    individual clients
    Am I missing something?
    My Code
    public class MultiServer {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = null;
            boolean listening = true;
            try {
                serverSocket = new ServerSocket(4444);
                System.out.println("MultiServer listening on Port 4444");
            } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(-1);
            // Indefinite Loop.
            while (listening)
             new MultiServerThread(serverSocket.accept()).start();
            serverSocket.close();
    public class MultiServerThread extends Thread {
        private Socket socket = null;
        public MultiServerThread(Socket socket) {
         super("MultiServerThread");
         this.socket = socket;
        public void run() {
         try {
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            socket.getInputStream()));
               BufferedReader stdInFromServer = new BufferedReader(new InputStreamReader(System.in));
            String fromTheClient,fromServer;
               fromServer = "Hi Client,How u doing? ";
            // Send a message from the Server.
               out.println(fromServer);
                while ((fromTheClient = in.readLine()) != null) {
                 if (fromTheClient.equals("ByeServer"))
                 break;
                 // Display message received from Client.
                 System.out.print("Client Response : ");
              System.out.println(fromTheClient);
                 // Input reply from the Server.
                 fromServer = stdInFromServer.readLine();
                 out.println(fromServer);
                 if (fromServer.equals("Bye."))
                    break;
             out.close();
             in.close();
             socket.close();
         } catch (IOException e) {
             e.printStackTrace();
    Client Code
    ===========
    public class Client {
        public static void main(String[] args) throws IOException {
            Socket kkSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                kkSocket = new Socket("localhost", 4444);
                out = new PrintWriter(kkSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: localhost.");
                System.exit(1);
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye."))
                    break;
                    fromUser = stdIn.readLine();
             if (fromUser != null) {
                    out.println(fromUser);
            out.close();
            in.close();
            stdIn.close();
            kkSocket.close();
    }

    Taking standard input for multiple threads from one console is quite unpredictable. I think the first client thread is waiting for input when you connect the second. You type something into your server window and since the first thread was waiting for input, it takes the input and sends it to client 1.

  • URGENT:Handle multiple connection in a multithreaded server.

    I hava a multithreaded server where it can handle multiple connection.
    The program works in this way. First, it will wait for connection. Once it accepts a connection, it will pass the socket to a thread class which will in turn process the connection. Then, the server will go back to the infinite loop to wait for new connection.
    Since I am not very familiar on using thread, I would like to post the following questions:
    1) Let say that my server can handle multiple connections. This is to cater for the different requests from the client. For instance, the client may make one connection for chatting and another connection for sending file(something like we have in Yahoo Messanger). So, at the server side, how can I differentiate between the connection for CHAT and the connection for SEND FILE so that I can handle the requests separately. It means I can save the file sent from client and display the chat message in the JTextArea?
    2) How can I stop the server, clean up the thread and start the server again for waiting new connection? Currently, I can just start my server once.
    For reference,following are parts of my program:
    public void listenSocket(){
    try{
    server = new ServerSocket(5000);
    } catch(IOException e) {
    System.out.println("Failed to listen on port 5000");
    System.exit(0);
    try{
    while(true){
    server1frame sframe=null;
    ChatHandler handler;
    handler = new ChatHandler(sframe,server.accept(),jTextArea1,jTextField1,jFileChooser1);
    handler.start();
    } catch(IOException e) {
    System.out.println("Accept failed:5000");
    System.exit(0);
    //to close the connection as the final steps before program exit.
    } finally {
    try{
    server.close();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    public void run() {
    out.println("Connection Established");
    out.flush();
    try {
    String line;
         while(!(line =in.readLine()).equalsIgnoreCase("QUIT")) {
    if(line.startsWith("CLIENT"))
    jTextArea1.append("\n"+line);
    else if(line.startsWith("Connecting")) {
    jTextArea1.append("\n"+line);
    else if (line.startsWith("Finish")) {
    JOptionPane.showMessageDialog(sframe,"File has finished downloading",
    "File Download Complete",JOptionPane.INFORMATION_MESSAGE);
    else {
    BufferedWriter fout = new BufferedWriter(
    new FileWriter("e:/num1.txt",true));
    fout.write(line);
    fout.newLine();
    fout.flush(); }
         } catch(IOException ioe) {
         ioe.printStackTrace();
         } finally {
         try {
              in.close();
              socket.close();
         } catch(IOException ioe){
    System.out.println("Fail to close connection.");

    1) Let say that my server can handle multiple
    connections. This is to cater for the different
    requests from the client. For instance, the client may
    make one connection for chatting and another
    connection for sending file(something like we have in
    Yahoo Messanger). So, at the server side, how can I
    differentiate between the connection for CHAT and the
    connection for SEND FILE so that I can handle the
    requests separately. It means I can save the file sent
    from client and display the chat message in the
    JTextArea?Either your server listens on two different ports for two different protocolls, (then you would a server thread for each port) or you accept connections for both protocolls on both ports, and have the client state what protocoll it is using :
    eg:
    accept Connection - start new Thread - read first line - depending on protocoll pass protocoll object (CHAT, FTP) to run method
    There is an example for a simple protocoll at : http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    2) How can I stop the server, clean up the thread and
    start the server again for waiting new connection?
    Currently, I can just start my server once.You normally start servers only once. It should then be up and listening for it's entire lifetime. Restarting a server should only be needed if it hangs or crashes.

  • Multithread server with futureTask

    i want to write a multithread server that prints the message received from a client in reverse order i have problems with getting the message from a client and passing that to futureTask
    this is my futureTaskCallback
    class FutureTaskCallback<V> extends FutureTask<V> {
    public FutureTaskCallback(Callable<V> callable) {
    super(callable);
    public void done() {
    String result = "Wynik: ";
    if (isCancelled()) result += "Cancelled.";
    else try {
    result += get();
    } catch(Exception exc) {
    result += exc.toString();
    JOptionPane.showMessageDialog(null, result);
    and mycallable
    public class MyCallable implements Callable
    String toReverse;
    public MyCallable(String s){toReverse=s;}
    public String call () throws java.io.IOException, InterruptedException {
         StringBuffer out = new StringBuffer();
         ////ClientWorker w;
    /// w = new ClientWorker(server.accept(), textField);
    /// Thread t = new Thread(w);
    //// t.start();
    //////toReverse=textField.getText();
         ///System.out.println(toReverse);
    if (toReverse == null || toReverse.trim().equals(""))
    throw new IllegalArgumentException("Set string to reverse");
    ///if (t.isInterrupted()) return null;
    char[] org = toReverse.toCharArray();
    //// if (t.isInterrupted()) return null;
    for (int i = org.length-1; i>=0; i--) {
    Thread.sleep(500);
    out.append(org);
    ////if (t.isInterrupted()) return null;
    ///textField.setText(out.toString());
    ////if (t.isInterrupted()) return null;
         ///////Thread t = Thread.currentThread();
    return out.toString();
    i want to pass the message received from a client to mycallable then to server so it can print the output
    how to do that ?
    thank you
    regards

    Here's a primitive example:
    import java.net.*;
    import java.util.concurrent.*;
    import java.io.*;
    import javax.swing.*;
    public class RevServer{
      ServerSocket ss;
      boolean go;
      public RevServer(int port){
        try{
          ss = new ServerSocket(port);
        catch (Exception e){
          e.printStackTrace();
        go = true;
      public void runServer(){
        try{
          while (go){
            Socket s = ss.accept();
            System.out.println("...client connected");
            service(s);
          ss.close();
        catch (Exception e){
          e.printStackTrace();
      void service(Socket s){
        Thread t = new Thread(new ClientHandler(s));
        t.start();
      public static void main(String[] args){
        RevServer rs = new RevServer(9999);
        rs.runServer();
    class ClientHandler implements Runnable{
      Socket sct;
      public ClientHandler(Socket s){
        sct = s;
      public void run(){
        try{
          BufferedReader br
           = new BufferedReader(new InputStreamReader(sct.getInputStream()));
          String msg = br.readLine();
          FutureTaskCallback<String> ftc
           = new FutureTaskCallback<String>(new MyCallable(msg));
          new Thread(ftc).start();
          PrintWriter pw = new PrintWriter(sct.getOutputStream(), true);
          pw.println(ftc.get());
          sct.close();
        catch (Exception e){
          e.printStackTrace();
    class FutureTaskCallback<V> extends FutureTask<V> {
      public FutureTaskCallback(Callable<V> callable) {
        super(callable);
      public void done() {
        String result = "Wynik: ";
        if (isCancelled()){
         result += "Cancelled.";
        else{
          try {
            result += get();
          catch(Exception exc) {
            result += exc.toString();
        JOptionPane.showMessageDialog(null, result);
    class MyCallable implements Callable<String>{
      String toReverse;
      public MyCallable(String s){
        toReverse = s;
      public String call() throws java.io.IOException, InterruptedException {
        StringBuffer out = new StringBuffer();
        if (toReverse == null || toReverse.trim().equals("")){
          throw new IllegalArgumentException("Set string to reverse");
       char[] org = toReverse.toCharArray();
        for (int i = org.length - 1; i >= 0; i--) {
          Thread.sleep(500);
          out.append(org);
    return out.toString();
    import java.net.*;
    import java.io.*;
    public class RevClient{
    public static void main(String[] args) throws Exception{
    String str, rstr;
    str = "All you need is love";
    if (args.length > 0){
    str = args[0];
    Socket sc = new Socket("127.0.0.1", 9999);
    PrintWriter pw = new PrintWriter(sc.getOutputStream(), true);
    BufferedReader br
    = new BufferedReader(new InputStreamReader(sc.getInputStream()));
    pw.println(str);
    System.out.println("...wait a moment");
    rstr = br.readLine();
    System.out.println(rstr);
    sc.close();

  • Logging for Multithread Server

    Hi Folks,
    I am trying to implement a simple logger for my Socket server and I have the following code working.
    public synchronized static void log(String msg) {
        DataOutputStream dos = null;
         Date dateValue;
         String dateTempString=new String();
        try {
              dateValue=new Date();
              SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM//hh-mm-ss");
              dateTempString = formatter.format(dateValue);
          dos = new DataOutputStream(new FileOutputStream("log.txt", true));
              dos.writeBytes(dateTempString+"\n"+msg+"\n");
              dos.close();
        } catch (FileNotFoundException ex) {
              } catch (IOException ex) {
      }Whenever I write something to console, I also call this function with the appropriate message.
    My question is that How to implement it for a multithreaded Server?
    In the log.txt file..there would be no way of knowing that which message belonged to which thread?
    Any Pointers here ?
    And Also, Is there a better way to do this simply?
    Thanks a lot to all you guys in advance...Looking forward to some good input.

    Hi
    dos = new DataOutputStream(new FileOutputStream("log.txt", true));
    dos.writeBytes(dateTempString+"\n"+msg+"\n");
    Can you change the second line to the following.
    dos.writeBytes(Thread.currentThread().getName + "\n"+dateTempString+"\n"+msg+"\n");
    Make sure that each thread that you create has a unique name.
    HTH
    VJ

  • A single UDP port in a multithreaded server

    I'm trying to write a server application that creates a thread for every client. The server/client communication is a combination of TCP and UDP, and I want to use a fixed TCP/UDP port on the server side to make it easier to use behind NAT routers. Here's a summary of what I have done and what I want to achieve:
    - The server creates a TCP and UDP channel (I'm using the NIO interface) on the specified ports
    - The server waits for incoming clients by calling accept() on the TCP channel
    - The server creates a new thread for the new client, and gives the TCP and UDP channels as arguments
    - The client informs the server about its UDP port over the TCP connection
    - The new server thread connect()s the UDP channel to the IP:port pair received over the TCP connection
    I believed that connecting the UDP socket to the IP:port of the client in each thread would make it possible to use a single UDP port for the multithreaded application, but it seems that the connect() call affects the parent thread as well. The next client that tries to connect() gets a "Connect already invoked" error. I tried calling clone() on the UDP channel argument I passed to the new thread, but was not allowed to call clone() because it's protected.
    Can someone tell me if what I'm trying to do is possible, and if so, how to achieve it?

    Peter__Lawrey wrote:It sounds like you want to bind a UDP socket to a listening port and the sender as well. So you can have a thread per sending IP:port. (Not sure why you would want to...)
    To my knowledge you can only bind a socket based on the listening port. You could have a dispatcher thread which passes these packets to the thread for that sender.
    To me, client/server means a request/response based interaction with a request from the client and the response from the server back to the client. This interaction is typically point to point and lossless.-I wanted one thread per client because it's the simplest thing to implement. For example, I don't have to create data structures for storing state information for each individual client (e.g., bitrate, block size, duration, etc), since each thread has only one single client. Still, I don't want to use hacks like having a dispatcher thread, so if it is correct that UDP ports can't be used in the same way as TCP ports, I guess I'll just have to implement the server as a single-threaded process. :(
    As for client/server, a better description would be master/slave (and that's what I'm using in my program), but I thought I'd make it simple and use the more common client/server terms in this thread since it doesn't matter for the question I'm asking.

  • Need help Multithread server

    hello all.,
    i need a help..,
    i wanna build a program that read from a socket, from a multiple client.., and a client can send multiple message..,
    when a client send a message, the system will proccess it, while the system proccess it can retrieve another request from the client..,
    i'm new at multithread socket programming,
    so what should i use..?,
    should i use server socket, or serversocket channel..???,
    help me..,
    regards..,
    odoyie

    You could have a look at the examples which come with the JDK under sample/nio/server
    Or you could look at my example [http://www.freshvanilla.org:8080/display/essence/Essence+Remote+Method+Invocation]

  • Multithreading server /- client doesnt update need a little help

    I have three classes, one is my client called lobby, the second is my server, then my third is the server thread. Everything works but the client doesnt seem to update unless you type stuff in and hit enter or press send and that isbecause of the key and action listeners, how do i go about having to updating every 10 seconds or less..? I tried doing a while statement and of course it freezed it because its an infinite loop, tried making it a thread, not to good at that, i just need some advice on how to solve this problem, thanks.
    public class Lobby extends JPanel {
         public Lobby()
              listenSocket();
              send = new JButton("Send");
              chatter = new JTextField();
              motd = new JLabel("The Lobby");
              this.setLayout(new MigLayout());
              this.setSize(800, 600);
              this.setBackground(Color.white);
              this.setAutoscrolls(true);
              this.add(motd, "span 1, align center");
              this.add(UserListTop(), "align center, wrap");
              this.add(ChatBox(), "");
              this.add(UserList(), "wrap");
              this.add(Chatter(), "");
              this.add(Send(), "");
              this.setVisible(true);
         public Component ChatBox()
              Dimension dscroll = new Dimension(590, 400);
              chatbox = new JTextArea(20, 50);
              chatbox.setLineWrap(true);
              chatbox.setEditable(true);
              chatbox.setWrapStyleWord(true);
              JScrollPane areaScrollPane = new JScrollPane(chatbox);
              areaScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              areaScrollPane.setAutoscrolls(true);
              areaScrollPane.setPreferredSize(dscroll);
              return areaScrollPane;
         public Component Chatter()
              KeyListener enter = new KeyListener()
                   @Override
                   public void keyPressed(KeyEvent event) {
                        if((event.getKeyChar() == KeyEvent.VK_ENTER) && (chatter.getText() != "") && (chatter.getText() != null))
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String());
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
                   @Override
                   public void keyReleased(KeyEvent e) {
                   @Override
                   public void keyTyped(KeyEvent e) {
              String line;
              try {
                   line = in.readLine();
                   chatbox.append("usernamehere: " + line + "\n");
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              chatter.addKeyListener(enter);
              Dimension chattersize = new Dimension(590, 30);
              chatter.setPreferredSize(chattersize);
              chatter.setVisible(true);
              return chatter;
         public Component Send()
              ActionListener sendl = new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent event) {
                        Object source = event.getSource();
                        if(source == send){
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String(""));
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  System.out.println("UserNameHere: " + line);
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
              send.addActionListener(sendl);
              send.setVisible(true);
              return send;
         public Component UserListTop()
              JLabel userlisttop = new JLabel("Players");
              return userlisttop;
         public Component UserList()
              Dimension scrollsize = new Dimension(170, 400);
              String names[] = new String[1500];
              for(int i = 0; i < 1500; i++)
                   names[i] = "Player" + i;
              userlist = new JList( names );
              userlist.setBackground(Color.white);
              userlist.setSize(50, 200);
              JScrollPane userlistscroll = new JScrollPane(userlist);
              userlistscroll.setPreferredSize(scrollsize);
              return userlistscroll;
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: localhost");
                   System.exit(1);
              } catch  (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
    }

    3rd class
    package server;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    // This client thread opens the input and the output streams for a particular client,
    // ask the client's name, informs all the clients currently connected to the
    // server about the fact that a new client has joined the chat room,
    // and as long as it receive data, echos that data back to all other clients.
    // When the client leaves the chat room this thread informs also all the
    // clients about that and terminates.
    import java.net.Socket;
    public class clientThread extends Thread{
        DataInputStream is = null;
        PrintStream os = null;
        Socket clientSocket = null;      
        clientThread t[];
        public clientThread(Socket clientSocket, clientThread[] t){
         this.clientSocket=clientSocket;
            this.t=t;
        public void run()
         String line;
            String name;
         try{
             is = new DataInputStream(clientSocket.getInputStream());
             os = new PrintStream(clientSocket.getOutputStream());
             os.println("Enter your name.");
             name = is.readLine();
             os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
             for(int i=0; i<=9; i++)
              if (t!=null && t[i]!=this)
              t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
         while (true) {
              line = is.readLine();
    if(line.startsWith("/quit")) break;
              for(int i=0; i<=9; i++)
              if (t[i]!=null) t[i].os.println("<"+name+"> "+line);
         for(int i=0; i<=9; i++)
              if (t[i]!=null && t[i]!=this)
              t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
         os.println("*** Bye "+name+" ***");
         // Clean up:
         // Set to null the current thread variable such that other client could
         // be accepted by the server
         for(int i=0; i<=9; i++)
              if (t[i]==this) t[i]=null;
         // close the output stream
         // close the input stream
         // close the socket
         is.close();
         os.close();
         clientSocket.close();
         catch(IOException e){};

  • Tic-tac-toe multithreaded server game

    i have written the code for tic-tac-toe game partially.i am stuck at writing the code for "who is the winner"? and adding a button to start the new game ?please help me out to write the remaining?
    iam unable to attach the code now;
    Message was edited by:
    vamshijupally

    i have written the code for tic-tac-toe game
    partially.i am stuck at writing the code for "who is
    the winner"? and adding a button to start the new
    game ?please help me out to write the remaining?That question is almost impossible to answer because you didn't provide two vital pieces of information.
    1) What specific problems you're having.
    2) Relevant code.
    iam unable to attach the code now;So, you call the doctor on the phone, say, "I'm not feeling well. Please make me better. I can't come to your office or tell you anything about what's wrong with me now."

  • Multithreaded sever client/server environment

    I understand sockets, socket streams, but what puzzles me is how one client can send to the server and the server send only to remaining clients connected. I though getPort() and IDs but I am clueless. Can I send across a socket to the server for broadcast, what do I do to have the server broadcast? Just write to the socket and have all clients continuously reading? How would a client get a chat message to the other clients? Would the server just send them through the socket and if so, how to prevent sending it back to sender client?
    I understand sockets and reader/writers through InputStream, OutputStream Scanner, and PrintWriter but the idea of what to do once clients connected to my multithreaded server baffles me. I want to be at one terminal and when I enter something on the sockets, all the remaining clients see it but just not connecting in my head.

    sabre150 wrote:
    Always Learning wrote:
    What am I missing?Don't know about what you are missing but I am missing a view of your code so can only guess at your problem. Guessing is not a very scientific approach to diagnosing problems.Sorry about that. I have posted it now ..
    This is the server .... I want to capture the sockets for use to broadcast client messages but just not working right
    public class is_TCPServer
         static final List<Socket> sockets = new CopyOnWriteArrayList<Socket>();
         // to send the same message to multiple sockets.
         public static void sendToAll(byte[] bytes) {
             for(Socket s: sockets)
               try {
                s.getOutputStream().write(bytes);
               } catch (IOException ioe) {
                // handle exception, close the socket.
                sockets.remove(s);
         public static void main(String[] args)
              int port = 0;
              boolean correctArguments = false;
              Scanner keyboard = new Scanner(System.in);
              // Process presence or absence of command-line arguments
              if (args.length > 0)
                   if (args[0].trim().equalsIgnoreCase("-p") && args.length > 1)
                        try
                             // Argument two must be an integer; port number
                             Integer.parseInt(args[1]);
                             System.out.println("Good Arguments");
                             correctArguments = true;
                        catch (NumberFormatException formatException)
                             // NAN
                             System.err.println("Bad arguments");
                   if (correctArguments)
                        // Success
                        port = Integer.parseInt(args[1]);
                   else
                        System.out.println
                                  ("usage: is_TCPServer [-p] [port - numeric value] \n");
                        System.out.print("Enter the desired port: ");
                        String temp = keyboard.nextLine();
                        try
                             port = Integer.parseInt(temp);
                        catch (NumberFormatException formatException)
                             System.out.println("Incorrect format, using default port");
                             // Set port to the default value
                             port = 8189;
              else
                   // Set port to the default value
                   port = 8189;
                   System.out.println("Using default port: " + port);
              try
                   // Establish the server socket on specified port
                   ServerSocket serverSocket = new ServerSocket(port);
                   System.out.println("Listening on port: " + port);
                   System.out.println();
                   File chatLog = new File("is_Chat.txt");
                   while (true)
                        // Server awaits client connection to accept
                        Socket clientConnection = serverSocket.accept();
                        sockets.add(clientConnection);
                        Runnable r =
                             new ServerThread(clientConnection, chatLog);
                        Thread t = new Thread(r);
                        t.start();
                        System.out.println("Listening on port: " + port);
              catch(IOException ioException)
                   ioException.printStackTrace();
    *               Handles the client input for one server socket connection
    class ServerThread implements Runnable
         private long initialTime;
         private long finalTime;
         private long days;
         private long hours;
         private long minutes;
         private long seconds;
         private long milliseconds;
         private File chatLog;
         private Socket incomingConnection;
         public final long DAYS_CONVERSION = 24*60*60*1000;
         public final long HOURS_CONVERSION = 60*60*1000;
         public final long MINUTES_CONVERSION = 60*1000;
         public final long SECONDS_CONVERSION = 1000;
         public ServerThread(Socket aSocket, File chatLog)
              this.chatLog = chatLog;
              incomingConnection = aSocket;
         public String elapsedTime(long finalTime)
              String elapsedTime = "";
              // Days
              if (finalTime > DAYS_CONVERSION)
                   // convert to days
                   days = finalTime / DAYS_CONVERSION;
              // remove the days from the total time
              finalTime = finalTime % DAYS_CONVERSION;
              // Hours
              if (finalTime > HOURS_CONVERSION)
                   // convert to hours
                   hours = finalTime / HOURS_CONVERSION;
              // remove the hours from the total time
              finalTime = finalTime % HOURS_CONVERSION;
              // Minutes
              if (finalTime > MINUTES_CONVERSION)
                   // convert to MINUTES
                   minutes= finalTime / MINUTES_CONVERSION;
              // remove the minutes from the total time
              finalTime = finalTime % MINUTES_CONVERSION;
              // Seconds
              if (finalTime > SECONDS_CONVERSION)
                   // convert to seconds
                   seconds = finalTime / SECONDS_CONVERSION;
              // remove the seconds from the total time
              finalTime = finalTime % SECONDS_CONVERSION;
              // compute the milliseconds
              milliseconds = finalTime % 1000;
              return elapsedTime += "Days: " + days + " Hours: " + hours +
                        " Mins: " + minutes + " Secs: " + seconds + " MS: " +
                                                                               milliseconds;
         public void run()
              try
                   try
                        // Record initial time
                        initialTime = System.currentTimeMillis();
                        // Establish input socket stream
                        InputStream inputSocketStream =
                                                   incomingConnection.getInputStream();
                        // Connect to the input socket stream
                        Scanner readSocketStream = new Scanner(inputSocketStream);
                        // Read the user name
                        String userName = readSocketStream.nextLine();
                        // Establish output socket stream
                        OutputStream outputSocketStream =
                                                 incomingConnection.getOutputStream();
                        // Connect to the output socket stream
                        PrintWriter writeSocketStream =
                                                 new PrintWriter(outputSocketStream);
                        // Establish a file writer to the chat log
                        PrintWriter fileWriter =
                               new PrintWriter(new FileOutputStream(chatLog, true));
                        // Open the chat log
                        Scanner fileReader = new Scanner(new FileInputStream(chatLog));
                        boolean done = false;
                        // Write client input to a chat log file
                        while(!done && readSocketStream.hasNextLine())
                             // Read the socket stream until user is finished
                             String clientInput = readSocketStream.nextLine();
                             if (clientInput.trim().equals("DONE"))
                                  done = true;
                             else
                                  is_TCPServer.sendToAll(clientInput.getBytes());
                                  synchronized(fileWriter)
                                       // Write client stream to the chat log file
                                       fileWriter.println(userName + ": " +
                                                                             clientInput);
                                       // Flush the writer
                                       fileWriter.flush();
                                  // Feedback on server end
                                  System.out.println(userName + ": " + clientInput);
                        // Close the chat log file
                        fileWriter.close();
                        // Close the chat log file
                        fileReader.close();
                        Chat file not to deleted
                        File file = new File(chatLog);
                        // Delete the chat log file
                        file.delete();
                        // Record the final time
                        finalTime = System.currentTimeMillis() - initialTime;
                        // compute and send session time to the client
                        writeSocketStream.println("\nSession length: " +
                                                                     elapsedTime(finalTime));
                        writeSocketStream.println();
                        System.out.println();
                   finally
                        System.out.println("Closing " +
                        incomingConnection.getInetAddress().getHostName() + ":"+
                                                                incomingConnection.getPort());
                        System.out.println();
                        // close the network connection
                        incomingConnection.close();
              catch(IOException ioException)
                   ioException.printStackTrace();
    }Edited by: Always Learning on Feb 18, 2012 3:34 AM

  • How to connect several clients to a server?

    Hi, i'm currently developing a client server based application. The problem i'm facing now is that i can only add one client. But i want to add every client that connects to the server. Do i need to assign each input and output stream to each connected clients?how do i do that? and will it be possible to add the connected client's name to a JList?
    Thanks in advance.

    You need multithreaded server.
    Look here:
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html#multi

  • Solaris 6 binary on Solaris 8 ( Multithreaded application.)

    I have to explore further, but I like to know whether any of you have faced similar problem.
    We have multithreaded server. A thread in detached mode will be created to serve each new connection. The binary was compiled on 32bit solaris environment and it was running fine on solaris 6 machines.
    Recently we switched to Solaris 8 machines. We used the same binary that was compiled on solaris 6. One problem I am noticing is some of the threads are idle and are alive for 3-4 days. We have timeouts enforced between successive transactions, inspite of that threads are alive for longer duration. We use "poll".
    Do you see any problem in Solaris 8 w.r.t Poll/Select syscall or Detached threads ( we use POSIX APIs) that were compiled on Solaris 6 ?.
    I would also like to give anyother information that would help you in identifying the problem.
    Thanks
    Mega

    we have ported our product to solaris 5.7 from solaris5.6. With this version we are unable to install the product on solaris 5.6. It is unable to find the following libraries in 5.6, while installing and finally it is failing.
    libMrm.so.4
    libXm.so.4
    libgen.so.3
    Is there any way to make my product work on both versions of solaris?

  • Enterprise User and Multi Thread Server

    Hi,
    We are going to build a system which uses a configuration:
    10g2
    Enterprise User
    Multi Thread Server
    Client apps accesses db over JDBC/SSL
    Could some please share experience about issues regarding
    using Enterprise User and Multi Thread Server ?
    Is MTS transparant for Enterprise User authentication ?
    Regards,
    Cezary

    If you build simpserv with -t, and set MIN and MAXDISPATCHTHREADS, you
    should have an example of a multithreaded server.
         Scott
    Johan Philippe wrote:
    >
    We have been going to the documentation on multi-threading and contexting in servers
    on Tuxedo 7.1.
    And the impression so far is that apart from the function definitions there is
    not much information around.
    Didn't even find a simple example of a multi-threaded server in the Bea refs yet.
    Does anyone know/have such an example?
    And is anyone using multi-contexting in a server, because the limitation that
    only server-dispatched
    thread get a context puts quite a limitation on its usefullness.

  • How does create a server with multiple Clients ?

    Any people can lead me .
    How does create a server with multiple Clients ?
    Thanks

    For a multithreaded server you will need a thread to listen and at least one thread per client. If the conversation is half duplex, one thread per client works very well, if it's full duplex you will find one thread to send and one to receive much easier to program.
    I posted a Simple Socket Server that uses 1+2*clients threads.

  • How to get started on java applet client/server game?

    Hi,
    I've googled, but didn't find any useful information about creating java applet client/server game. I've followed the example of Client/Server Tic-Tac-Toe Using a Multithreaded Server in Java How to Program from Deitel, but I when I tried on Applet, my cliet doesn't communicate with the server at all. Any help to get started with Applet would be great. Thanks!

    well, i decided to put in portion of my codes to see if anyone can help me out. the problem I have here is the function excute() never gets called. here is my coding, see if you can help. Notice, I'm running this on Applet thru html page. This shouldn't be much different than running JFrame in term of coding right?
    Server.java
        public void init()
            runGame = Executors.newFixedThreadPool(2);
            gameLock = new ReentrantLock();
            otherPlayerConnected = gameLock.newCondition();
            otherPlayerTurn = gameLock.newCondition();
            players = new Player[2];
            currentPlayer = Player1;
            try
                server = new ServerSocket(12345, 2);
            catch (IOException ie)
                stop();
            message = "Server awaiting connections";
        public void execute()
           JOptionPane.showMessageDialog(null, "I'm about to execute!", "Testing", JOptionPane.PLAIN_MESSAGE);
            for(int i = 0; i < players.length; i++)
                try
                    players[i] = new Player(server.accept(), i);
                    runGame.execute(players);
    catch (IOException ie)
    stop();
    gameLock.lock();
    try
    players[Player1].setSuspended(false);
    otherPlayerConnected.signal();
    finally
    gameLock.unlock();
    Client.java
        public void init()
            startClient();
        public void startClient()
            try
                connection = new Socket(InetAddress.getByName(TienLenHost), 12345);
                input = new Scanner(connection.getInputStream());
                output = new Formatter(connection.getOutputStream());
            catch (IOException ie)
                stop();
            ExecutorService worker = Executors.newFixedThreadPool(1);
            worker.execute(this);
        }So after worker.execute(this), it should go to Server.java and run the function execute() right? But in my case, it doesn't. If you know how to fix this, please let me know. Thanks!

Maybe you are looking for

  • Retrieve XMLP documents directly from BLOB fields in E1; Tools Release 8.97

    Hi, I want to be able to retrieve XML Publisher reports (PDF, RTF, HTML) directly from the database BLOB fields in EnterpriseOne. Instead of making users manually save each report to get a soft-copy of the report, I wanted to be able to retrieve the

  • Filename problem while invoking process (com.adobe.idp.dsc.RequiredParameterException)

    Hello, We have a working process that's being triggered by an email endpoint. For every PDF attachment that is being sent to a specific address, 1 instance of the process is being started. This works fine. However, when the filename of the PDF attach

  • Help required for the users  report requirement

    Hello, User requirement is to get the report as follows Period            planned order     Production order      Backlog Feb2008          15                           3                      18 March2008      4                            11          

  • Png button image not display properly

    i have create two png image one for default and one for selected i assing both image to button view... but when run it to simulator as well as on iphone it will not display clear png image

  • Where are photos saved

    i just upgraded from 10.4 to 10.6.3 and successfully imported all my old documents to a new machine. i'm wondering where the iphoto library is saved in iphoto 9. in my old version, in the pictures folder, there was an iphoto library folder with all m