Multiple client threading "NullPointerException"

Hello Java Forum World :)
Coming up to a problem that should be simple...I think. But I can't get through it. I have a simple chat program, and some GUI that goes along with it. The program is an application, so the applet examples I've tried havent been working for me. ...well for that matter...the application examples arent working either. I think the problem is somehow related to the threading? Its either not receiving the data, or not sending it. Could anyone please look at my code? :)
3 Files
-Client
-MultiServer
-MultiServerThread
***Client***
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends javax.swing.JFrame implements Runnable
   private String message = "";
   private String chatServer;
   private Socket client;
   private int port = 4444;
   boolean DEBUG = true;
   Socket socket;
   String host = "127.0.0.1";
   boolean trysted;
    DataOutputStream o;
    DataInputStream i;
    protected Thread listener;
  protected TextArea output;
  protected TextField input;
    /** Creates new form Client */
    public Client( String host, InputStream i, OutputStream o ) {
       super("Client");
       i = new DataInputStream (new BufferedInputStream (i));
       o = new DataOutputStream (new BufferedOutputStream (o));
        initComponents();
       chatServer = host; // set server to which this client connects
       setSize( 300, 650 );
       setVisible( true );
        listener = new Thread (this);
       listener.start();
   public void start()
   } // end method runClient
/////// send message to server
   private void sendData( String message )
   { System.out.println("sendData()"+message);
     try {
          o.writeUTF ( message );
          o.flush ();
     } catch (IOException ex) {
          ex.printStackTrace();
          listener.stop ();
     //input.setText ("");
    private void initComponents() {
        jInternalFrameChat = new javax.swing.JInternalFrame();
        jTextFieldCompose = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPaneConversation = new javax.swing.JScrollPane();
        jTextAreaConversation = new javax.swing.JTextArea();
        jInternalFrameDraw = new javax.swing.JInternalFrame();
        jInternalFrameTextSymbols = new javax.swing.JInternalFrame();
        jButtonTextSymbolPlus = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemQuit = new javax.swing.JMenuItem();
        jMenuConnecton = new javax.swing.JMenu();
        jMenuItemDisconect = new javax.swing.JMenuItem();
        getContentPane().setLayout(new java.awt.FlowLayout());
        setTitle("Whiteboard");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
        jInternalFrameChat.setTitle("Chat");
        jInternalFrameChat.setName("intFrameChat");
        jInternalFrameChat.setPreferredSize(new java.awt.Dimension(200, 200));
        jInternalFrameChat.setVisible(true);
        jTextFieldCompose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
               sendData( jTextFieldCompose.getText() );
               jTextFieldCompose.setText( "" );
        jInternalFrameChat.getContentPane().add(jTextFieldCompose, java.awt.BorderLayout.NORTH);
        jButton1.setText("Send");
     jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
               sendData(jTextFieldCompose.getText() );
               jTextFieldCompose.setText( "" );
        jPanel1.add(jButton1);
        jButton2.setText("Insert Symbol");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
        jPanel1.add(jButton2);
        jInternalFrameChat.getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
        jTextAreaConversation.setColumns(2);
        jTextAreaConversation.setLineWrap(true);
        jTextAreaConversation.setWrapStyleWord(true);
        jScrollPaneConversation.setViewportView(jTextAreaConversation);
        jInternalFrameChat.getContentPane().add(jScrollPaneConversation, java.awt.BorderLayout.CENTER);
        getContentPane().add(jInternalFrameChat);
        jInternalFrameDraw.setTitle("Draw");
        jInternalFrameDraw.setPreferredSize(new java.awt.Dimension(230, 233));
        jInternalFrameDraw.setVisible(true);
        getContentPane().add(jInternalFrameDraw);
        jInternalFrameTextSymbols.getContentPane().setLayout(new java.awt.FlowLayout());
        jInternalFrameTextSymbols.setPreferredSize(new java.awt.Dimension(130, 133));
        jButtonTextSymbolPlus.setText("+");
        jButtonTextSymbolPlus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTextSymbolPlusActionPerformed(evt);
        jInternalFrameTextSymbols.getContentPane().add(jButtonTextSymbolPlus);
        getContentPane().add(jInternalFrameTextSymbols);
        jMenuFile.setText("File");
        jMenuItemQuit.setText("Quit");
        jMenuItemQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemQuitActionPerformed(evt);
        jMenuFile.add(jMenuItemQuit);
        jMenuBar1.add(jMenuFile);
        jMenuConnecton.setText("Connection");
        jMenuItemDisconect.setText("Item");
        jMenuConnecton.add(jMenuItemDisconect);
        jMenuBar1.add(jMenuConnecton);
        setJMenuBar(jMenuBar1);
        pack();
    private void jButtonTextSymbolPlusActionPerformed(java.awt.event.ActionEvent evt) {
        jTextFieldCompose.setText(jTextFieldCompose.getText()+"+");
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        jInternalFrameTextSymbols.setVisible(true);
    private void jTextFieldComposeActionPerformed(java.awt.event.ActionEvent evt) {
       jTextAreaConversation.setText(jTextAreaConversation.getText()+'\n'+"Student: "+jTextFieldCompose.getText());
       jTextFieldCompose.setText("");
    private void jMenuItemQuitActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        System.exit(0);
       public static void main( String args[] ) throws IOException
        {System.out.println("main");
          if (args.length != 2)
      throw new RuntimeException ("Syntax: ChatClient <host> <port>");
    Socket s = new Socket (args[0], Integer.parseInt (args[1]));
    new Client ("Chat " + args[0] + ":" + args[1],
                    s.getInputStream (), s.getOutputStream ());
     public void run() {
          try {
               while (true) {
                    String line = i.readUTF ();
                    output.appendText (line + "\n");
          } catch (IOException ex) {
               ex.printStackTrace ();
          } finally {
               listener = null;
               //input.hide ();
               validate ();
               try {
                    o.close ();
               } catch (IOException ex) {
                    ex.printStackTrace ();
}// end run
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonTextSymbolPlus;
    private javax.swing.JInternalFrame jInternalFrameChat;
    private javax.swing.JInternalFrame jInternalFrameDraw;
    private javax.swing.JInternalFrame jInternalFrameTextSymbols;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuConnecton;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemDisconect;
    private javax.swing.JMenuItem jMenuItemQuit;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPaneConversation;
    private javax.swing.JTextArea jTextAreaConversation;
    private javax.swing.JTextField jTextFieldCompose;
}***MultiServer***
import java.net.*;
import java.io.*;
class MultiServer
     public MultiServer (int port) throws IOException {
          ServerSocket server = new ServerSocket (port);
          while (true) {
               Socket client = server.accept ();
               System.out.println ("Accepted from " + client.getInetAddress ());
               ChatHandler c = new ChatHandler (client);
               c.start ();
  public static void main (String args[]) throws IOException {
    if (args.length != 1)
      throw new RuntimeException ("Syntax: MultiServer <port>");
    new MultiServer (Integer.parseInt (args[0]));
}*** MultiServerThread ***
import java.io.*;
import java.net.*;
import java.util.*;
class MultiServerThread extends Thread
     protected Socket s;
     protected DataInputStream i;
     protected DataOutputStream o;
     public MultiServerThread(Socket s) throws IOException {
          this.s = s;
          i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
          o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
     protected static Vector handlers = new Vector ();
     public void run () {
          try {
               handlers.addElement (this);
               while (true) {
                    String msg = i.readUTF ();
                    broadcast (msg);
          } catch (IOException ex) {
               ex.printStackTrace ();
          } finally {
               handlers.removeElement (this);
               try {
                    s.close ();
               } catch (IOException ex) {
                    ex.printStackTrace();
     protected static void broadcast (String message) {
          synchronized (handlers) {
               Enumeration e = handlers.elements ();
               while (e.hasMoreElements ()) {
                    ChatHandler c = (ChatHandler) e.nextElement ();
                    try {
                         synchronized (c.o) {
                              c.o.writeUTF (message);
                         c.o.flush ();
                    } catch (IOException ex) {
                         c.stop ();
} // end class

changed Client.constructor()--    public Client( String host, InputStream is, OutputStream os ) {
       super("Client");
       this.i = new DataInputStream (new BufferedInputStream (is));
       this.o = new DataOutputStream (new BufferedOutputStream (os));----
changed MultiServer.constructor()--MultiServerThread  c = new MultiServerThread  (client);----
changed MultiServerThread.broadcast()--MultiServerThread c = (MultiServerThread) e.nextElement ();----
Error at Client.class:
java Client 127.0.0.1 4444
main
sendData()a
java.lang.NullPointerException
at Client.run(Client.java:215)
at java.lang.Thread.run(Unknown Source)
Error at MultiServer.class:
Accepted from /127.0.0.1
Accepted from /127.0.0.1
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at MultiServerThread.run(MultiServerThread.java:23)
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at MultiServerThread.run(MultiServerThread.java:23)
Error at other Client.class instance:
main
java.lang.NullPointerException
at Client.run(Client.java:215)
at java.lang.Thread.run(Unknown Source)

Similar Messages

  • 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 on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

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

  • How can I connect multiple clients to a single client ?

    I am currently developing an instant messaging program.I created a server and connected multiple clients to it by using thread logic.However I do not know how to connect multiple client to a single client.
    What shall I do for that?Does anybody know a good tutorial or sample program?Or shall anybody explain me what I shall do for building the Instant Messaging part of my chat program?
    Thank u in advance.

    You may use UDP multicast socket. But since you are using the UDP protocol you might risk losing the data that you send since UDP does not guarantee the safe transfer of data.
    Alternately, you might create a server that allows multiple client to connect to it whose connection Socket objects are then stored in a Vector <Socket> object. The server then sends back data to the connected client about the other clients connected to it. Now when the client wants to send data (like an IM) to another connected client, it has to send a request to the server specifying the client login name and the server in turn streams that particular client's Address and Port to the requesting client. The requesting client then initiates the connection with the other client and then starts a conversation. One more thing, when the client communicates it needs to send information to the server like the name by which it likes to be referenced. In this scenario the server acts like a central repository for clients to query the existence of other clients in the chat room. Each client here runs a thread that listens to incoming connections and when a connection is established, may be opens a IM window or something.
    The third option is to make the server to relay the information from one client to another. Like say, I'm connected to whoopy server and i want to send "Hello" to jackson, then i send the message (ie, Hello) along with the name of the client to which i wish to send it to (ie, jackson). The server then performs a lookup in its Vector <Socket> object and then initiates a connection with jackson and sends the information. However, this method is pretty costly in that you will be wasting a lot of processing behind the server.
    --Subhankar
    P.s. If you stumble upon any other brilliant ideas let me know.

  • How to handle multiple clients with DatagramSocket

    I am trying to handle multiple clients with 1 datagramSocket bind to one port (basically I have only one port to use, and I can not use TCP or any other ports). At the server side I have two threads one for receiving packets and buffering them, another for processing the packets in the buffer and sending replies.
    I can have multiple clients sending datagramPackets to me and I will have to process the packets and send them to DIFFERENT clients. Ex. Client 1 sends datagramPacket to Server which sends the processed packet to Client 2. Also Client 2 sends a datagramPacket to Server which again processes the packet and sends it to Client1. May have Client 3 and 4 doing the same thing at the same time... and so on...
    My root class is creating the datagramSocket(somePort) and two threads (receiver and sender). How can I use the socket that I created in these two threads??
    I have done the following and I am getting "java.net.bindexception". When I am sending stuff from Client1 to Client2 everything is fine but when I start sending something from Client2 to Client 1, I get the bindexception... Client 1 is using port 3000, Client 2 is using port 4000.
    I really don't have a lot of experience in socket programming so I am not sure if there is a much simpler way to do this. I appreciate all the tips and help that I can get...
    Thanks...
    class UDP_serv
         static DatagramSocket udpSocket;
         final static int SERVER_PORT     = 2000;
         public static void main(String[] args) throws SocketException
              udpSocket= new DatagramSocket(SERVER_PORT);
              new DataReceiver().start ();
              new DataSender().start ();
         static class DataReceiver extends Thread
              DataReceiver()
                   Thread.currentThread().setName("DataReceiver");
              public void run()
                   while (true)
                        byte pckt[] = new byte [MaxMsgSize];          
                        DatagramPacket dp = new DatagramPacket (pckt, pckt.length);
                        try
                             udpSocket.receive (dp);
                             //PUSH TO RECEIVE BUFFER
                        catch(Exception e)
                             e.printStackTrace();
         static class DataSender extends Thread
              DataSender()
                   Thread.currentThread().setName("DataSender");
              public void run()
                   while (true)
                        processDataMsg();
          static void processDataMsg() 
             DatagramPacket op;
             InetAddress DA = null;
             int DP = 0;
             byte [] outPacket = null;
             // POP FROM RECEIVE BUFFER
             // SOME PROCESSING HERE     
             // Set Destination Address (DA)
             // Set Destination Port (DP)
             // DA and DP are the forwarding IP and Port addresses
             // not the addresses original packet was sent from.
             try
              op = new DatagramPacket (outPacket, outPacket.length,DA, DP);
              udpSocket.send(op);
             catch (IOException e)
              e.printStackTrace();
    }Also for development and testing purposes, I am running the two clients and the server on the same machine (windows xp-32b) so all of the Destination IP Addresses are 127.0.0.1. and as I said Ports that I am using are 2000, 3000, 4000 (Server, Client1, Client2).

    Hmm I have minimized the code and it seems to be working now.
    I think I have an error in the header portion of the data I am sending, where I am storing the source IP/Port and destination IP/Port. I think the server in the middle is messing these values up while sending them to the destination Client. Because the destination client actually receives the stuff and sends the reply back to the server, but the reply packet's headers has 0/0 as the dest IP / Port...
    Server is giving me java.net.BindException: Cannot assign requested address error when it tries to forward the reply it received from the client2 as the address it is trying to send is 0!
    I guess it doesnt just give this error when you try to open two sockets to the same port...
    Paul, Thanks for the direction on how to proceed... took me a while get the minimized code but at least figured out the problem. Well still have to make sure that is THE problem though :)
    As far as the statics goes how can I change those to non static ones? Where do I make an instance of the top level class that creates the threads? and how do I pass the DatagramSocket to the threads/ if I dont need to pass how do I call or use the datagramSocket I created in the top level class? I mean do I still kinda have it like a global variable on the top?? A very simple example would be much appreciated...
    I think these might be really basic questions but I am having a rough time with the hierarchy in java...

  • TES 6.1.0.x Multiple Client Managers

    Hello:
    I am trying to find out if there is anyone else using multiple client managers on a load balancer and if we could have a discussion regarding such a setup. We have this in our envrionment and it does work, however sometimes I see oddities with in the client - even if I log directly into one of my client managers, by-passing the load balancer completely.
    Looking forward to hearing from anyone with a similar setup.
    Regards,
    Ceceil Rufo

    We haven't done a formal load testing yet.  But we have conducted training with 10 - 15 users and would experience performance sometimes people just getting kicked out.  At the time though we were still finagling with server configuration settings for threads, cache and java heap.  During training too what seemed to impact performance more was the browser and version, and workstation memory.  For a web app, TES 6.1 uses a LOT of memory so there were some suggested tweaks that had to be done on some machines.  We have more consistent performance on IE 9 (than IE 10), and Firefox 18+ was faster.
    I have installed Jconsole and am planning to conduct load testing sometime this month where i could monitor server resource from Jconsole to get an idea where bog down really is. 
    There is a TES 6.1 presentation doc that sort of outlines approx sizing based on concurrent users - we fit in the 10 -20 concurrent users given that our CM has 12GB RAM (allocated 10GB to TES) and 4 core.  So hopefully with two CMs we can have upto 40.  We are open to adding more mem if needed.  So what tools do you use for Load testing?  Also I wonder if it was possible to automate Load Testing like with Jmeter or something.  For now we just plan on getting 20 users together to perform set functions at the same time and measure that with 1 CM up and me looking in Jconsole.
    I also notice the multiple connections, even see myself twice even when I only have 1 browser session.  Not having had a chance to dig to deeply i was chalking it up to maybe that I didn't exit properly last time so that it has to wait 30 minuts to totally clear me (with time to live setting) out but haven't really tested formally.  I will see about adding that to my testing.  I would also think it would impact system in that some folks may cause the number of concurrent connections allowed to be exceeded if you have too many of these lying around but since they are not doing anything perhaps not performance as much?  It will be good to confirm though that a single web session really only takes 1 connection and won't potentially spawn another somehow.
    Our implementation being highly distributed with workgroups having full autonomy over their jobs - means every team needs to have access to Transporter.  We have over 15 teams. Which is scary since that also takes resources from the CM -  and also from a management and training perspective.  We also haven't load tested the Transporter server interms of number of concurrent users that can be running Transporter on it at one time.  Nor have any clear idea yet how we'll manage the mapping files.  But we are also opening up Transporter to be installed by teams on their team server (only that they have to patch themselves) - I really wonder if we should just restrict Transporter access to just the servers our team manage and no one else can install it anywhere else.

  • Multiple clients in DEV and QA for CHARM setup

    Blog /people/dolores.correa/blog/2008/07/26/first-steps-to-work-with-change-request-management-scenario is an excellence introduction to CHARM setup.
    However in real world, we have multiple clients on DEV and QAS systems.
    Could you help explain how to extend the method in above blog to multiple DEV and QAS clients?
    Thanks !

    Hi Diana,
    Please have a look at this thread :
    Kind regards,
    Stéphane.

  • 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 anyone show me an example of multiple clients(RMI)?

    Hi.
    Can anyone show me one simple example of a server serving multiple clients using RMI?
    I know that I have to use thread but I'm not really use to it...
    Thank you :)

    You don't have to use threads, you don't have to do anything. Any RMI server will service multiple clients simultaneously.

  • One Server Multiple Clients

    Hello,
    This server code accepts only one client connection at a time. However, I have several lines that are specifically for the server to accept more than one client. What do I need to do in addition for the server to recognize that it can accept more than one client at a time?
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    import javax.swing.JFrame;
    public class ServerTest
       public static void main( String args[] )
          Server application = new Server();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          application.runServer();
    class Server extends JFrame
       private JTextField enterField;
       private JTextArea displayArea;
       private ObjectOutputStream output;
       private ObjectInputStream input;
       private ServerSocket server;
       private Socket connection;
       private int counter = 1;
       private ExecutorService serverExecutor;
       private MultiServer clients[];
       public Server()
          super( "Server" );
          enterField = new JTextField();
          enterField.setEditable( false );
          enterField.addActionListener(
             new ActionListener()
                public void actionPerformed( ActionEvent event )
                   sendData( event.getActionCommand() );
                   enterField.setText( "" );
          add( enterField, BorderLayout.NORTH );
          displayArea = new JTextArea();
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
          setSize( 300, 150 );
          setVisible( true );
       public void runServer()
          serverExecutor = Executors.newCachedThreadPool();
          try
             server = new ServerSocket( 12345, 100 );
             while ( true )
                try
                   waitForConnection();
                   getStreams();
                   processConnection();
                catch ( EOFException eofException )
                   displayMessage( "\nServer terminated connection" );
                finally
                   closeConnection();
                   counter++;
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void waitForConnection() throws IOException
          displayMessage( "Waiting for connection\n" );
          connection = server.accept(); 
          serverExecutor.execute( new MultiServer(server, connection));     
          displayMessage( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() );
       private void getStreams() throws IOException
          output = new ObjectOutputStream( connection.getOutputStream() );
          output.flush();
          input = new ObjectInputStream( connection.getInputStream() );
          displayMessage( "\nGot I/O streams\n" );
       private void processConnection() throws IOException
          String message = "Connection successful";
          sendData( message );
          setTextFieldEditable( true );
          serverExecutor.execute(new MultiServer(server, connection));
          do
             try
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
             catch ( ClassNotFoundException classNotFoundException )
                displayMessage( "\nUnknown object type received" );
          } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
       private void closeConnection()
          displayMessage( "\nTerminating connection\n" );
          setTextFieldEditable( false );
          try
             output.close();
             input.close();
             connection.close();
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void sendData( String message )
          try
             output.writeObject( "SERVER>>> " + message );
             output.flush();
             displayMessage( "\nSERVER>>> " + message );
          catch ( IOException ioException )
             displayArea.append( "\nError writing object" );
       private void displayMessage( final String messageToDisplay )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   displayArea.append( messageToDisplay );
       private void setTextFieldEditable( final boolean editable )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   enterField.setEditable( editable );
      class MultiServer extends Thread
      public MultiServer(ServerSocket servers, Socket connection)
          servers = server;
      public void run(){System.out.print("Yes");}
    }

    Check out the "Supporting Multiple Clients" bit here: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    Start a Thread for each client. I'd recommend you create a class:
    class Client
        Socket socket;
        ObjectOutputStream out;
        ObjectInputStream in;
        ...any other client-specific data you need...
        public void sendMessage(String s) { ...send to this client...; }
       ...any other client-specific methods you need...;
    }Create one of those when accept() gets a new connection, then start the thread for that client.
    You may want to keep a LinkedList that contains all the Client objects. E.g. if you want to send a message to all clients you'd loop over the LinkedList and send to each in turn. Synchronize the list appropriately. Removing clients from the list when they close down can be interesting :-) so be careful.

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

  • Send data to multiple clients from a server

    My problem statement is this:
    A server is created, say X. Multiple clients are created, say A, B & C. If X sends a message to A it should reach only A and should not go to B or C. Similarly if X sends message to B it should not reach A or C. I made a one to one communication with the following code:
    //Server
    import java.io.*;
    import java.net.*;
    class X
    public static void main(String args[])throws Exception
    ServerSocket ss=new ServerSocket(4321);
    try
    Socket s=ss.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    String str=in.readLine();
    out.writeBytes(str+"\n");
    s.close();
    ss.close();
    catch (IOException e){}
    //Client A
    import java.io.*;
    import java.net.*;
    class A
    public static void main(String args[])throws Exception
    try
    Socket s=new Socket("localhost",4321);
    BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
    System.out.println(in.readLine());
    s.close();
    catch(Exception e){}
    }But i dont know how to keep track of each client. Because all the clients sockets are created at the same port, ie. 4321. I think thread will help. But even then i dont know how to identify each client. Somebody please help. Thanks in advance.
    Edited by: sowndar on Dec 5, 2009 1:21 AM

    YoungWinston wrote:
    sowndar wrote:
    Ok. I think i have to attach an unique ID to each client message. So that, with the help of that ID, the server can identify each client. Have i caught ur point?If you don't mind using a port per client, you could do something like a receptionist taking incoming calls (on 4321 only).
    - Hi I'm Client xyz.
    - Hi Client xyz, please call me back on port abcd and I'll put you straight through to our server.
    Since 4321 is an "open line" you might have to have some sort of ID so that Clients know which return messages are meant for them, but messages on the other ports would all be direct Client to Server. Also, the Server is then is charge of port allocation and communication on the "open" port is kept to a minimum.4321 is the socket that the server is listening to. It's not what the actual communication will be carried out over. Run this, then telnet to port 12345 a few times
    public class TestServerSocket {
      public static void main(String[] args) throws Exception {
              ServerSocket server = new ServerSocket(12345);
              while (true) {
                   Socket socket = server.accept();
                   System.err.println(socket.getPort());
    }Notice how each inbound connection is allocated a unique outbound socket.

  • Calling pl/sql api through multiple java threads

    Hi All,
    I need to call a pl/sql api from multiple java threads simultaneously and all thread will use same db connection.
    I want to know if all the threads will simultaneously call the pl/sql api then will the local variable inside pl/sql procedure be shared between them or they will get separate instances of variables.
    TIA

    You cannot make multiple parallel client calls over the same Oracle session handle. There is a single non-threaded/non-fibre serialised server process servicing client requests for that session. (physical process on Linux/Unix, thread in the oracle.exe process on Windows).
    Each thread on the client side, needs its very own Oracle session. Thus each thread will have a server process footprint on the server. Which could be problematic if 10 clients each starts 10 threads - as it means a 100 processes on the server are needed to service these client threads.
    Have a look at Overview of OCI Multithreaded Development in the Oracle® Call Interface Programmer's Guide for how to use the threading call interface of the OCI - as oppose to rolling your own where each thread manually needs to deal with is OCI session context.

  • Networking: problems servering multiple clients

    hi all
    i'm writing a simple client server system, with a multithread server, in order to serve multiple clients.
    the client's requests to connect to the server arrive to a port (ie 1025), and then the server, through a method returns to the client another port number, and then the comunication between them starts through the new port.
    all work very fine, but i tried, with 2 computers, to start two clients at the "same time" (with a gap of few milliseconds), and my system "crashes".
    i think that is a problem due to the second request that arrives while the comunication of the port from the server to the client happens.
    is there a way to "queue" the requests arriving to the 1025 port of my server?
    if i wasn't clear i can post some code
    thanx in advance
    sandro

    Yes, teh code I posted does nothing more then listen for incoming conections and create a new Thread wich gets the Socket created by the accept to play with. This will happen for any incoming connection on the right port and will always be handeled the same.
    As you'll see in the code i posted, there is some time between ServerSocket.accept returning a Socket and ServerSocket.accept being started again. This time shouldn't be to long to be sure the serversocket is listening for incoming connections when they arrive, so don't do to much inside the loop. If your system should handle a lot of connections simultaneously wou might have to optimise this be doing thing like having a few ClientThreads created allready to save the time of creating a new Thread. This becomes more important if you ClientThread is complex and slow to create. But when handelin less the say 25 clients you should be fine with this.

Maybe you are looking for