Multiple client chat server

Thanks to the help I got from the good people of this forum today I modified the chat server program which I am making and now it is working a bit better. Right now it can accept several (up to 8) clients and store their open sockets in a SocketCollection list which can later be accessed so that messages get sent to all of them. Problem is that when I send a message, it is displayed instantaneously on the client that sent that message (my machine), but is displayed only after the other clients press enter on the other clients' machines (for testing purposes it was the same machine, different port opened for communication with server which is also on the same machine). To clarify that - all clients and server are the same machine (that shouldn't be a problem, right?). Code for printing incoming data for client program is below:
while ((fromServer = in.readLine()) != null) {
            if (fromServer!=null){
                   System.out.println(fromServer);
                   System.out.println("print on client screen msg received from server");
            fromUser = stdIn.readLine();
            if (fromUser != null) {
          System.out.println("Client: " + fromUser);
          out.println(fromUser);
}Code to deliver the message to all clients from the server application is below as well:
while ((inputLine = in.readLine()) != null) {
                 PrintWriter multiOut;
               for (int x=0; x<8; x++){
                     System.out.println("INSIDE MULTI-TELL FOR LOOP");
                     if (socketCollection[x]!=null){
                           Socket c=socketCollection[x];
                           try{
                               System.out.println("tried to send to all\nSocket c = " + c);
                               out=new PrintWriter(c.getOutputStream(), true);
                                   out.println(c.getInetAddress() + inputLine);
                            catch(IOException ioe){}
}In the server's DOS window I can clearly see that it enters to display the message to multiple clients and it should send it. The sockets are all different and they point to different ports on different clients' machines. Maybe the problem is just in the client program's code. If you could help me out, it will be greatly appreciated. Thank you very much.

The sockets get created one by one when each client connects. Afterwards when the thread is made, that socket gets copied into the SocketCollection array which can afterwards be accessed in order for the server to distribute the message to all its connected clients.
The for loop in the second code example where it takes SocketCollection[x] and gets its outputStream and all that is where it prints the message and sends it to each client (sends it but it is not displayed on the client side until the client sends a message to the server again). My question is how to make it so the client does not have to send a message in order to see the server message (message to all clients) that was sent before.

Similar Messages

  • Need help in setting up a Multi Client chat server.

    I've been stuck at this problem longer than I should be, and it's starting to get to me.
    In my quest to learn more about networking in Java, I've decided to start with a simple multi client chat program. The problem is that I don't know exactly how to go about setting it up.
    I can't think of any way for multiple threads to be able to send data to the central server so that can then be sent to every other client, and also be able to request data and have it sent back just to the client that requested it.
    I think part of my problem might be that my knowledge of threads is somewhat limited, and that I might be overlooking or over complicating something.

    If you're trying to develop webapplications then I'm not too sure if SunONE 6.1 is the best platform considering that its support for jsp, servlets and the likes is rather outdated. Personally I'd look into http://www.sun.com/download/products.xml?id=446518d5 (Java webserver 7 rc3) if you wish to continue using a webserver with integrated java container.
    Otherwise you might benefit more from https://glassfish.dev.java.net (project glassfish), which is naturally also included in the http://java.sun.com/javaee (Java EE5).
    Just my 2 cents.

  • Multiple-client, same server, different configurations

    Hi experts,
    Recently we have got a project of IS-U Electricity where it has been planned that the same server we used for the last project will be used for this upcoming project where the configurations are diffrent from each other but both of them will run together in same development, quality and production servers.
    My question is whether we would be able to configure sap as per the requirements for the upcoming project to a particular client whereas the rest of the clients will use old configurations for the existing project in the same server. Will there be any cross-client configuration conflicts?
    - Arghya

    Arghya:
    The answer to this question is unrelated the industry solution.  Multiple client scenarios are used in many solutions.  Some configuration is client dependent and so would be different in each client; other configuration is client independent and would be used in all clients.  That would be part of the analysis to determine if multiple clients or multiple systems is the correct approach.
    regards,
    bill.

  • File transfer to multiple clients from server socket

    I have multiple clients connected to my server socket and I need to copy more than 200mb documents from server to all clients over socket. Can we design the issue considering scalability and performance factor? What I am thinking of we should use thread for transferring file from server to client. But at the same time if we have large number of clients then we can't initialize a thread for each client. I think in this case we should initialize less than 10 threads in the pool as the file size is very large. If we keep number of threads in the pool low then probably we have to read multiple times the large server file (once for each group) which might again be a performance bottleneck. Please pour in your suggestions.

    File would be same for an instance only. For example say I have a "SEND File" button & �File Path� text box. In File Path suppose user enters the absolute path of the file and then clicks on Send File button. The responsibility of Send File button would be sending the file mentioned in the "File Path" text box to all connected client. But next time user can choose a different file.

  • Multiple client single server problem(it hangs halfway)

    TestThread Class
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.Timer;// for timer
    import java.util.TimerTask;//for timer
    public class TestThread {
      public static void main(String[] args) {
        DataInputStream inputFromClient1;
        DataOutputStream outputToClient1;
        DataInputStream inputFromClient2;
        DataOutputStream outputToClient2;
        ServerSocket serverSocket = null;
        System.out.println("MastermindServer started at " + new Date() + "\n");
        try {
          serverSocket = new ServerSocket(8000);
        } catch(IOException ex) {
          System.err.println(ex);
        try {
          Socket socket = serverSocket.accept();
          System.out.println("sc1 connected \n\n\n\n");
          inputFromClient1 = new DataInputStream(socket.getInputStream());
          outputToClient1 = new DataOutputStream(socket.getOutputStream());
          String startMessage = "Two players now,You can start multiGame!";
          outputToClient1.writeUTF(startMessage);
          outputToClient1.writeUTF("hehehe");
          outputToClient1.writeUTF("hahaha");
          Socket socket1 = serverSocket.accept();
          System.out.println("sc 2 connected \n\n\n\n");
          inputFromClient2 = new DataInputStream(socket1.getInputStream());
          outputToClient2 = new DataOutputStream(socket1.getOutputStream());
          outputToClient2.writeUTF(startMessage);
          outputToClient2.writeUTF("hehehe");
          outputToClient2.writeUTF("hahaha");
    //problem starts here when both are not received
          System.out.println("Problem starts here");
          int y = new DataInputStream(socket.getInputStream()).readInt();
          System.out.println("message from client 1 : "+ y);
          int x = new DataInputStream(socket1.getInputStream()).readInt();
          System.out.println("message from client 2 : "+ x);
          outputToClient1.writeUTF("1  hehehe");
          outputToClient1.writeUTF("1  hahaha");
          outputToClient2.writeUTF("1  hehehe");
          outputToClient2.writeUTF("1  hahaha");
        } catch(IOException ex) {
          System.err.println(ex);
    }testSocket class
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.border.Border;//for borders
    import javax.swing.border.LineBorder;//for border lines
    import java.awt.event.ActionEvent;//for action event
    import java.awt.event.ActionListener;//for action listener
    import javax.swing.*;
    import java.util.*;
    import java.util.Timer;// for timer
    import java.util.TimerTask;//for timer
    public class testSocket {
      public static void main(String[] args) {
        new testSocket();
      public testSocket() {
           DataOutputStream outputToServer;
        DataInputStream inputFromServer;
        try {
          // Create a socket to connect to the server
          Socket socket = new Socket("localhost", 8000);
          inputFromServer = new DataInputStream(socket.getInputStream());
          outputToServer = new DataOutputStream(socket.getOutputStream());
          String message = inputFromServer.readUTF();
          System.out.println(message);//start mess
          message = inputFromServer.readUTF();
          System.out.println(message);//hehehe
          message = inputFromServer.readUTF();
          System.out.println(message);//hahaha
          message = inputFromServer.readUTF();
          new DataOutputStream(socket.getOutputStream()).writeInt(99);     
          System.out.println(message);
          message = inputFromServer.readUTF();
          System.out.println(message);
        } catch (IOException ex) {
          System.err.println(ex);
        System.out.println("connected liao");
    }Problem description:-
    I simplified this problem from my long code into 2 test files with the problem only.
    TestThread.java is the server
    testSocket.java is the client
    Running TestThread.java first then run testSocket twice without closing any would only show that it executes till line 46 and refuses to run further
    It would execute the TestThread till line 38 and not go further.
    Any help with this problem? Say I delete line 38 of testSocket and line 49-52 of TestThread, it would work fine but wouldn't work with input from different clients which would result in the program to hang there. I need to have input and output from different clients to the server at different time and interchangeable from one client to the other. In my program, the clients does different jobs so use of threads is out of the question.

    I found your mistake.
    Your clients are trying to receive a message that server has not sent.
    String message = inputFromServer.readUTF(); //read start message
    System.out.println(message);//start mess
    message = inputFromServer.readUTF(); //read hehehe message
    System.out.println(message);//hehehe
    message = inputFromServer.readUTF(); //read hahaha message
    System.out.println(message);//hahaha
    message = inputFromServer.readUTF(); //<<----- what message? hangs waiting a server message
    new DataOutputStream(socket.getOutputStream()).writeInt(99);      //this is not executed
    ...And your server hangs wait your clients int.
    Anyway, you should not recreate the DataOuputStream! use the objects you've already create.
    Lines 49 to 52 on server should be:
    int y = inputFromClient1.readInt();
    System.out.println("message from client 1 : "+ y);
    int x = inputFromClient2.readInt();
    System.out.println("message from client 2 : "+ x);It also applies to your client, see line 40.
    Regards,
    Henrique Abreu

  • Making a chat server that supports multiple clients!

    This is what I got so far:
    import java.net.*;
    import java.io.*;
    public class Server{
         public static void main(String [] args){
              ServerSystem ssys = new ServerSystem();
              ssys.ServerMethod();
    class ServerSystem{
         static ServerSocket ss;
         public void ServerMethod(){
              try{
                   ss = new ServerSocket(27700);
                   boolean listening = true;
                   for(;listening;){
                        ClientThread ct = new ClientThread(ss.accept());
                        ct.start();
                        ss.close();
              }catch(Exception e){
                   System.exit(0);
    class ClientThread extends Thread{
         ServerSystem ssys = new ServerSystem();
         ServerSocket ss = ssys.ss;
         public void run(){
              try{
                   BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream()));
                   PrintWriter out = new PrintWriter(ss.getOutputStream(),true);
              }catch(Exception e){
                   System.out.println(e);
    }3 Errors:
    ClientThread ct = new ClientThread(ss.accept()); CONSTRUCTOR : CANNOT RESOLVE SYMBOL
    BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream())); METHOD : CANNOT RESOLVE SYMBOL InputStream
                   PrintWriter out = new PrintWriter(ss.getOutputStream(),true); METHOD : CANNOT RESOLVE SYMBOL OutputStream
    First of all, how do I fix those. Second, am I on the right track for a server that supports multiple clients? Please help me with this.
    Thanks!

    well, since I feel kinda bad for just re-posting the link to the API docs previously posted by supermicus I shall elaborate - though, since my reading for comprehension skills are clearly lacking, I will not attempt to teach you to read.
    This conversation should be held in the "New to Java Technology" forum, BTW.
    Java derives a lot of its power from the huge library of classes that ships with it, which is called the API. These classes are grouped into packages roughly along functional lines, so you should expect to see some relationship between the classes found in a given package - the java.net.* classes all pertain to networking. The API documentation describes three things about each class - fields that are available, constructors that you can use, and methods that you can call. Basically, anything at all that you can do with a given class (ThreadGroup, for instance) can be found in the documentation for that class. Typically (for non-static classes), you call the constructor that seems most appropriate via the "new" keyword, and, using the reference returned from that, you call the method that does what you want. It's all outlined in the docs.
    If you don't get what you need from the docs, then read the appropriate Tutorial (also in the list of links to the left of your screen) find the one on Threads and off you go.
    I hope this helped.
    Lee

  • My simple chat server does not send messages to connected clients

    Hi!
    I´m developing a chat server. But I can not get it work. My client seems to make a connection to it, but my server does not send the welcome message it is supposed to send when a client connects. Why not?
    removedEdited by: Roxxor on Nov 24, 2008 10:36 AM

    Ok, I solved my previous problem and now I have got a new really annoying one.
    This is a broadcasting server which meand it can handle multiple clients and when one client sends a message to the server, the server should broadcast the message to all connected clients. It almost works, except that the server just sends the message back to the last connected client. The last connected client seems to steal the PrintStream() from the other clients. How can I solve that?
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.lang.Character;
    import java.io.OutputStream;
    import java.util.Vector;
    public class ChatServer extends MIDlet implements CommandListener, Runnable
         private Display disp;
         private Vector connection = new Vector();          
         private TextField tf_port = new TextField("Port: ", "", 32, 2);               
         private Form textForm = new Form("Messages");
         private Form start_serverForm = new Form("Start server", new Item[] {  tf_port });
         private Command mExit = new Command("Exit", Command.EXIT, 0);
         private Command mStart = new Command("Start", Command.SCREEN, 0);
         private Command mDisconnect = new Command("Halt server", Command.EXIT, 0);
         ServerSocketConnection ssc;
         SocketConnection sc;
         PrintStream out;
         public ChatServer()
              start_serverForm.addCommand(mExit);
              start_serverForm.addCommand(mStart);
              start_serverForm.setCommandListener(this);
              tf_port.setMaxSize(5);
              textForm.addCommand(mDisconnect);
              textForm.setCommandListener(this);
         public void startApp()
              disp = Display.getDisplay(this);
              disp.setCurrent(start_serverForm);
         public void pauseApp()
         public void destroyApp(boolean unconditional)
         public void commandAction(Command c, Displayable s)
              if(c == mExit)
                   destroyApp(false);
                   notifyDestroyed();
              else if(c == mStart)
                   Thread tr = new Thread(this);
                   tr.start();
              else if(c == mDisconnect)
                   try
                        sc.close();                              
                   catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
                   destroyApp(false);
                   notifyDestroyed();
         public void run()
              try
                   disp.setCurrent(textForm);
                   ssc = (ServerSocketConnection)Connector.open("socket://:2000");
                   while(true)               
                        sc = (SocketConnection) ssc.acceptAndOpen();     
                        connection.addElement(sc);                                                  
                        out = new PrintStream(sc.openOutputStream());
                        textForm.append(sc.getAddress() + " has connected\n");
                        ServerToClient stc = new ServerToClient(sc);
                        stc.start();
              catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
              catch(NullPointerException err) { System.out.println("NullPointerException error: " + err.getMessage()); }
         class ServerToClient extends Thread
              String message;
              InputStream in;
              SocketConnection sc;
              ServerToClient(SocketConnection sc)
                   this.sc = sc;
              public void run()
                   try
                        in = sc.openInputStream();
                        int ch;
                        while((ch = in.read())!= -1)                         
                             System.out.print((char)ch);
                             char cha = (char)ch;                              
                             String str = String.valueOf(cha);                    
                             out.print(str);
                             //broadcast(str);
                             textForm.append(str);                              
                        in.close();
                        //out.close();
                           sc.close();
                   catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
    }

  • Chat Server and Client Design

    Ola,
    I just want to make a simple Chat Program for intranet (LAN). I'm planning to use socket connection. What would be a good design for Chat Program? Both the Client and the Server are Java Application.
    Here is the diagram that I have in mind:
    ---- First the client login to Server:
    [Client A] ----> [Server]
    [Client B] ----> [Server]
    ---- Then Server add client in the container, Server put each connection from client to separate Thread, so it can handle multiple clients.
    ---- Then let's say Client A send message to Client B (or others). Server get the message from Client A, and my problem is how to get the Server to send the message to B. The only way that I know is to make each client act like its own server and listening to certain port number. That way the server can send the incoming message directly to the client.
    [Client A] ------> [Server] -----???---> [Client B]
    At this point I just have the Server listening to a port (ex. 10000). Should I have each client listening to a port number?
    Another design that I have in mind is to have only Server listening to port 10000. And have the client to poll the Server (ex. every 2 seconds) to check whether the server has new message for the client.
    The last design that I was considering is using RMI.
    Which approach that will best fit my case? What is the ideal design for making chat client server program? If you know any URL or Books that explains all these issue, please post them here. Any help will be appreciated.

    My approach (with tcp sockets) was the following:
    The server has two serversockets running.
    The client connects at the first one, which it will use
    for sending (any messages) and receiving a reply from the
    server ( an "ok" confirmation or so) .
    The client then connects at the second serversocket,
    which it uses for listening to the server.
    The second socket then also can be used for "alive" calls
    from the server periodically ( to kick out users, who
    have lost connection silently)
    Also the second socket, of course, is used as broadcast channel.
    Broadcasted messages can contain chat messages, information
    about a user, which has logged in or out ..
    When the server receives a (chat)message from a client, it
    first enters that message in its model and then broadcasts
    this message ( or more generally the changes in its model)
    to all clients including the client, who has
    sent the message, which only displays the message, when he
    has received it back from the server.
    This way, the order of messages displayed is the same for
    all clients - its a sort of synchronization process.
    Also, you don't need different ports ( for anything in principle ).
    Port 80 is enough.
    For multiple connections, you can send an integer as first
    data transfer, which acts as "virtual portnumber" and the
    receiver then can forward the socket to the associated threads.
    One thing to note for the broadcast process is, that you
    can't simply broadcast the messages in a loop, because this
    way, one veeery slow client would slow down the whole
    server. Therefore you will have to use threads for that.
    In the old (jdk1.3) way, the server would create a thread
    for each user who connects at the first serversocket,
    pass the socket (which it gets from the accept() method )
    to that thread, and this thread then would block while
    trying to receive, and after it had received something,
    it would call a synchronized method from the server,
    in which the server datamodel would be updated and
    broadcasts would be started ( in an other thread context ).
    A good way to speed up chat systems with heavy load is
    to use MultiCast sockets. But then you would have to
    use Datagrams (UDP).
    Another problem arises, when you want to go through
    firewalls. RMI has probs, and bidirectional transfer
    isn't allowed (some firewalls allow 1 request followed by
    1 answer and then cut the connection to my knowlegde)
    It's possible, but it's more complicated.

  • Multiple Clients in Client/Server Program

    I'm currently trying to make a small Client/Server application that will mimic a very basic chat room program. The basic idea is that the Server side of the program is started and multiple Client programs can connect and communicate with each other. However, I'm having a few problems at the moment, mostly with figuring out how it can work.
    Firstly, I can communicate one to one with the server and the client as the client socket is stored in a variable. However, to make it possible to allow multiple connections I've used a thread for each new connection but I'm not sure how I can broadcast messages to every connection. Would it be safe enough to store each client socket in a list and then communicate that way? Not sure what will happen when the client disconnects though it seems to be an issue.
    I'm also not sure how every message can be broadcasted to every single connections to the server. The server program can send a message to every client but the clients message at the moment only goes to the server. Anyway here's a bit of my code so far:
    SwingWorker<Socket, Void> worker = new SwingWorker<Socket, Void>() {
            protected Socket doInBackground() throws Exception {
                // Client socket
                try {
                    while (!stopRequested) {
                        clientSocket = serverSocket.accept();
                        // Stop requested is checked twice because the accept() method
                        // waits for a connection
                        if (!stopRequested) {
                            HostFrame.getFeedbackTextArea().append("New Connection Found");
                            Thread clientThread = new HandlerThread(clientSocket);
                            clientThread.start();
                        else {
                            serverSocket.close();
                            clientSocket.close();
                catch (Exception e) {
                    HostFrame.getFeedbackTextArea().append("Failed to Connect with Client");
                    System.out.println(e.getMessage());
                return clientSocket;
        };The SwingWorker is used so that the GUI doesn't freeze when the server tries to find a connection. At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client. Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets. Any help would be much appreciated

    clientSocket = serverSocket.accept();'clientSocket' should be a local variable here.
    else {
    serverSocket.close();
    clientSocket.close();You shouldn't close 'clientSocket here'. All you're accomplishing is closing the most recently accepted client socket. What about the others? Generally speaking you should let the client-handling threads take care of their own sockets completely.
    return clientSocket;This return statement is meaningless. You may as well return null. SwingWorker doesn't care. Don't just return something because you've got it lying around. In this case you shouldn't have it lying around.
    At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client.That is exactly what you have to do to handle more than one client. Once you fix it as per above.
    Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets.You probably need to keep a Map of client sockets accepted, keyed by some client identifier.

  • How to control one server with multiple clients via TCP/IP

    I am wanting to control a single server with multiple clients.  Only one client would be active at a time, so there would be no conflict.  I want to use TCP/IP.  So far, I have programmed a cluster that passes data back to the server with no problems.  The challenge come in when a second client is added to the mix.  I have't been able to figure out how to turn each client on and send the appropriate data and then turn it off so it doesn't keep sending the same data to the server. 
    Here are the things that I have considered and did some preliminary testing, but don't really know how to impliment:
    1.  Send a numeric on the front of the cluster packet that tells the server that data is on the way.
    2.  Send a boolean on the front of the cluster packet to somehow turn the server TCP/IP on.
    The problem I have found is that LabVIEW TCP/IP doesn't like to be turned on and off.  If it doesn't get the data it expects, it goes into a reset mode and that kills the response time.
    Any help?

    You should consider implementing a set of simple one-byte commands that can be sent back and forth between the Server and the Clients. You can base all of these ideas off the example in the Example Finder under Networking >> TCP and UDP called Multiple Connections - Server.
    You will have two loops in the server VI: one to wait for new connections, and one to send and receive data from the existing connections. For instance, after one of the clients connects, it can request control of the server to send data to it by sending the character "R" for request. Every time the send/receive loop of the Server executes, the first thing it can do is to check all the existing connections to see if any of the clients have sent a control request ("R"). If so, it will create a buffer (array) of control requests. This could be in the form of Connection IDs or indexes in the array for a particular Connection ID. Your choice.
    After the Server receives a request for contol, if it is not already under control by another client, then it can send a response to the first client on the control request list. For instance, the server could send the first client a "S" command for send. Note that after the clients send their control request, they should execute a TCP Read and wait indefinitely for the server to respond with the one-byte "S" command. Then, once the client in control is finished sending data to the server, it could send the character "X" telling the Server to release it from control.
    The example I mentioned above already does a similar thing. Note how when a client wants to disconnect, they send the letter "Q". You can see this in the Multiple Connections - Client VI. The Server then checks each individual connection to see if it's received this one-byte command, and if it has, it closes the connection to the client. This is what you would want to implement, but instead of having just one command, you'll have to distinguish between a few and build up a buffer of control requests.
    Finally, if a client does decide to disconnect in your application, they could send the command "Q" just like the example above. At this point, close the connection and remove that Connection ID from the array of connections. You will also have to handle the case that this client was in the request control waiting line when it disconnected, in which case you need to delete it from that array as well.
    This will definitely work for you, but it will take some work. Best of luck!
    Jarrod S.
    National Instruments

  • Saving string  from multiple clients on a server data structue

    I have a server which receives updates from multiple clients ( in this example, football scores which are updated periodically by the clients.)
    When the server receives the scores it needs to store them and at certain time intervals send the complete list of scores to multiple terminals at various locations.
    I am approaching this task in stages...
    stage 1.
    ..create the clients and server ...test the clients can send the data and the server can receive the data and output to screen..
    this is completed
    stage 2...
    a/ on the server side store the received scores in a data structure (ArrayList<String> is what I'm thinking.)
    b/ periodically output all scores to the screen (maybe every 30 seconds) and empty the ArrayList..am looking at the Timer class for this part..
    stage 3
    create the monitors and output scores to monitors periodically..
    ======================================================
    right now I'm at stage 2a ie trying to store the received scores in a data structure.
    i've created a method saveScore in the StoreScore class which is called by the StoreScore run method...
    The saveScore method creates an ArrayList and adds the score to it...
    Question
    does every thread create a new instance of storedScores and therefore the scores are stored in a multitude of data structures?
    I think the answer is yes and if so then this is not the solution...
    What I'm thinking is , as all scores can be outputted to the server screen via System.out.println, is there not a way of saving all these scores in a single data structure?
    The code below is the server code..
    any advice much appreciated....thank you
    /*=============================================================== */
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.*;
    class ScoresServer1{
    final static int portNum = 1234; // any number > 1024
    final static int numThreads = 10;
    static ExecutorService pool;
    public static void main(String[] args){
    pool = Executors.newFixedThreadPool(numThreads);
    System.out.println("Server running ...");
    try{  
    ServerSocket servesock = new ServerSocket(portNum);
    // for service requests on port
    while (true){ 
    // wait for a service request on port portNum
    Socket socket = servesock.accept();
    // submit request to pool
    pool.submit(new StoreScore(socket));
    }catch(IOException e){}
    class StoreScore implements Runnable {
    BufferedReader reader;
    Socket sock;
    public StoreScore(Socket clientSOcket) {
    try {
    sock = clientSOcket;
    InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
    reader = new BufferedReader(isReader);
    } catch (Exception ex) { ex.printStackTrace(); }
    public void run() {
    String message;
    try {
    while ((message = reader.readLine()) != null) {
    // System.out.println("latest score: " + message);
    saveScore(message);
    } catch (Exception ex) { ex.printStackTrace(); }
    public void saveScore(String message){
         ArrayList<String> storedScores = new ArrayList<String>();
         storedScores.add(message);
         Iterator<String> t = storedScores.iterator();
              while(t.hasNext()){
                   String s = t.next();
                   System.out.println(s);
    }

    does every thread create a new instance of storedScores and therefore the scores are stored in a multitude of data structures?
    I think the answer is yes and if so then this is not the solution...The answer is yes. However, threads can share data, if they were properly synchronized. You should read the threading tutorial before creating a lot of hard to debug mistakes.
    [http://java.sun.com/docs/books/tutorial/essential/concurrency/]

  • Multiple clients with same account on a single IMAP server

    Hi,
    I am connecting to a IMAP server using same account but from 2 different machines. From one machine a mark a message as SEEN=FALSE. But on the second machine, the flag will still be TRUE.
    Is there any way to co-ordinate between multiple clients so that all the clients are in sync.
    Regards,
    Nitin.

    I was able to resolve the problem using addMessageCountListener and messagesAdded method, as suggested by you.
    I am now facing another problem. Whenever a new message is received, code inside messagesAdded method gets executed. Here I am trying to spawn another thread and do some stuff. But this new thread is not starting at all. It goes into some JavaMail:EventQueue and does nothing. What is the concept of EventQueue here? How can I get this new thread executed?
    Also will there be synchronization problems in messagesAdded method. Say I received a message and I am processing it in the messagesAdded method. In the mean time another message comes up. How will this behave.

  • Lync 2010 client connecting to 2013 persistent chat server

    Since we never had Group Chat in our 2010 environment, I have no idea how it works and now that we have 2013 Persistent Chat, I am struggling with getting the Lync 2010 connected. The 2013 client works just fine as it is integrated into the client. I found
    out Lync 2010 needs a separate Chat client to run along side the IM client.
    I installed this client but from there I have no idea how to connect it to the 2013 Chat server. I created the endpoint on the Lync 2013 server according to the article
    http://technet.microsoft.com/en-us/library/jj204901.aspx but something else needs to be done. I just don't know what. Not even sure where to start looking. Many of our Lync clients have
    to use 2010 because the OS is XP so I need to find out how to get these users to work with Persistent Chat.
    I am not sure what the point is of creating the End point according to the article. I am sure its necessary but not sure how it fits into the clients using it to connect. What does the article mean when it says "Next, configure Persistent Chat clients
    to use that SIP address as their contact object". Do you need Group Chat functioning in 2010 for this to even work?
    The problem is we never had Group Chat with 2010 so I am sure there are some settings missing like DNS records etc...

    If you have users running legacy clients (such as Microsoft Lync 2010 these users might find the default Persistent Chat URIs difficult to work with and difficult to use when pointing their legacy client towards the pool. Because of this,
    administrators need to use the New-CsPersistentChatEndpoint cmdlet to create an additional contact object for the pool, a contact object that provides a friendlier, easier-to-use URI.
    Lisa Zheng
    TechNet Community Support

  • 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.

  • Can I broadcast multiple video chats using Adobe flash player and "RED5 flash server"?

    Hello...
    I've just joined today, and I had a question about RED5 & Adobe... Does anyone know if it is possible to broadcast multiple video  chats using Adobe flash player from "RED5 flash server"?
    Thanks,
    P.delafortune

    I am not sure whether any one of us has experience with RED 5 server - it would be best if you can post of RED 5 forums and try to get solution to your query. If you have any related query with respect to FMS - please feel free to post again.

Maybe you are looking for

  • XML, XSLT and Omniportlet

    Hello, I hope I can find some help. Using 10.1.14. I'm importing an XML document. I don't know if it's in rowset/row format (don't know what that is). I use XSL to transform it. When I click "test", I see pretty much what I want. A table tag, a td wi

  • Best way to extract strings

    Hello, I need to extract the value of the strings for REQUEST_GROUP_CODE and REQUEST_GROUP_APPL_SHORT_NAME. As you can see I have to deal with whitespace differences, case differences etc. I need the values between the quotes for each one. I would ex

  • Difficulty in WS_security

    I am using Workshop vesrion 8.1.4. I have coded an application exactly similar to the security.wsse.reqResp.mycompany.MyCompany & security.wsse.reqResp.client.Client in sample directory which comes with Workshop. I am using the exactly the same key s

  • Why does Messages app automatically start whenever I receive an imessage?

    I'm using my mac to try and get some work done, and as a result have apps such as messages closed (I'm trying to focus.) I even have pop-up notifications disabled in the notification center. However, whenever I receive an imessage messages.app automa

  • Firefox is working VERY SLOW the last 5 days(Signature: hang | )

    in the last 5 days i am experiencing terrible slowness to load firefox and during its function it loads very slow every page i choose.