Server/client IO ArrayList

So, I have this client and server classes which work like that� Server just starts and waits for a client to connect, then the client �sends� a String which represents a username for that client. Server then stores the username in an ArrayList called usersList. It also stores the ObjectOutputStream(the server side ObjectOutputStream) of this connection in a HashMap called outStreamMap and then sends back to every connected client that ArrayList. The code is:
Server:
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
public HashMap<String,ObjectOutputStream> outStreamMap;
public ArrayList<String> usersList;
public Server(){
  usersList=new ArrayList<String>();
  outStreamMap=new HashMap<String,ObjectOutputStream>();
  CallReceiver cr=new CallReceiver();
public static void main(String[] args){
  Server serv=new Server();
class CallReceiver implements Runnable{
ServerSocket serverSocket;
public CallReceiver(){
  try{
   serverSocket=new ServerSocket(5432);
   Thread callReceiverThread=new Thread(this);
   callReceiverThread.start();
  }catch(IOException e){e.printStackTrace();}
public void run(){
  while(true){
   try{
    Socket socket=serverSocket.accept();
    InputStream is=socket.getInputStream();
    OutputStream os=socket.getOutputStream();
    ObjectOutputStream objOutStr=new ObjectOutputStream(os);
    ObjectInputStream objInStr=new ObjectInputStream(is);
    Object obj=objInStr.readObject();//reads the username
    String username=(String)obj;
    usersList.add(username);//adds the user to the ArrayList
    outStreamMap.put(username,objOutStr);//adds the output stream to the Map
    for(String user:usersList){//sends the ArrayList to every user
       outStreamMap.get(user).writeObject(usersList);
       outStreamMap.get(user).flush();
       System.out.println("Sent ArrayList:"+usersList+" to:"+user);
   }catch(Exception e){
      e.printStackTrace();}
}//end of CallReceiver
}//end of server
Client:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client{
public Client(){
  try{
   Socket socket=new Socket("127.0.0.1",5432);
   OutputStream outStr=socket.getOutputStream();
   InputStream inStr=socket.getInputStream();
   ObjectOutputStream objOutStr=new ObjectOutputStream(outStr);
   ObjectInputStream objInStr=new ObjectInputStream(inStr);
   objOutStr.writeObject("John");//sends a string representing a username
   objOutStr.flush();
   ArrayList userlist;
   while(true){
     Object obj=objInStr.readObject();//reads an object wich actually is an ArrayList
     userlist=(ArrayList)obj;
     System.out.println("ArrayList received: "+userlist);
  }catch(Exception e){e.printStackTrace();}
public static void main(String[] args){
Client cl=new Client();
}The client all it does is just waiting for an ArrayList and then just prints it on the command line.
Lets say for example that you run a client with username, john. You get on the command line something like:
ArrayList received: [john]
Then you connect a second client with username, george (the first client is still connected, offcourse).
So, you get on the first client�s command line:
ArrayList received: [john]
And on the second client�s command line:
ArrayList received:[john, george]
And so it goes, if you connect another one you get on the first�s [john], on the second�s [john, george] and on the third�s [john, george, mike]. And this is the problem I cannot understand how this is happening since the server �sends� the exact same ArrayList object to all clients! Please someone more openeyed than me help me!!

This is due to ObjectStream caching, instead of resending the data, it will only send a marker (as in 'object foo sent again'). It doesn't know that the contents of the object are changed.
This is due to the fact that ObjectStreams aren't really supposed to be used this way, and this way if you're writing the same object many times, it'll save on the bandwidth (it'll send only the backreference).
Look at the writeUnshared() method in ObjectOutputStream.

Similar Messages

  • Need an example of server / client program with swing interface

    Hi!
    After a lot of trying i still haven't managed to create a server client program using swing components ...
    can someone write a mini application to demonstrate how this can be done?
    i would like to have a frame with a button a texField for input and a textAread for the output
    What i have in mind is the following ..
    say im the server
    i write something in the textField and then i press the button
    then the information written in the textFiled is passed to the client who shows it in his textArea
    The same thing goes on with the client (he can write something in his own textField and when he presses the button the info is passed at the
    server who puts it in his textArea) and vice versa.
    i have written many classes that trying unsuccessfully to do that ... below i show my last attempt ...
    I would appreciate if you could write a small application which it could to this.
    The whole idea is to create a turn based game ( i have implemented the game engine and graphics and i try to add the internet function)
    Here is the code ...( i would appreciate if you write a new code instead of trying to correct mine ( which i think it's impossible) in order to use it as a general example)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    *  In order to have a more gereral program instead of passing strings between the server
    *  and the client a pass an MyObjext object.  The MyObject class has an integer and a String
    *  (which is always the same) field . At the textField i write an integer number and i
    *  make a new MyObject which i want to pass to the server or the client and vice versa.
    *  The textArea shows the integer value of the MyObject which was passed from the server /client
    public class MyUserInterface extends JFrame {
         MyObject returnObject;
         JTextField myTextField;
         JTextArea te ;
         ClientGame cg;
         ServerGame sg;
          * used to determine if the current instance is running as a client or host
         boolean isHost;
         //The constructor of the client
         public MyUserInterface(ClientGame cg){
              this("Client");
              this.cg = cg;
              isHost = false;
         //The constructor of the server
         public MyUserInterface(ServerGame sg){
              this("Server");
              this.sg = sg;
              isHost = true;
         //The general constructor used both by client and server ..
         // it initializes the GUi components and add an actionListenr to the button
         public MyUserInterface(String str) {
              super(str);
              myTextField = new JTextField(2);
              te = new JTextArea();
              te.setPreferredSize(new Dimension(100,100));
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        try{
                             int a = Integer.parseInt(MyUserInterface.this.myTextField.getText());
                             System.out.println(a);   //used to control the flow of the program
                                  MyUserInterface.this.returnObject = new MyObject(a);
                             //sends the data
                             sendData();
                             //waiting for response...
                             getData();
                             catch(Exception ex){System.out.println("Error in the UI action command" +
                                                                ex.printStackTrace();}
              JPanel panel =  new JPanel(new FlowLayout());
              panel.add(okButton);
              panel.add(myTextField);
              panel.add(te);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         protected MyObject getReturnObject() {
              return returnObject;
         public void sendData(){
              new Thread(new Runnable() {
                   @Override
                   public void run() { 
                        if (!isHost)cg.sentData(returnObject);    //using the Servers out and in methods
                        else sg.sentData(returnObject);                    //using the Clients out and in methods
                        System.out.println("data sending");
         public MyObject getData(){
              MyObject obj;
              System.out.println("Retrieveing Data");
              if (!isHost)obj = (MyObject)cg.getData();
              else obj = (MyObject)sg.getData();
              System.out.println(" data retrieved  = "+ obj.getInt());  //just to control how the code flows
              te.setText(obj.getInt()+"");       
              return obj;
         public static void main(String[] args) {
              *Initiating the Server
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ServerGame sg = new ServerGame();
                        new MyUserInterface(sg);
              }).start();     
               * Initiating the Client
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ClientGame cg = new ClientGame("192.168.178.21");   //<----in case you run my code
                                                                          //..don't forget to change to your
                        new MyUserInterface(cg);                              //ip
              }).start();
    import java.io.*;
    import java.net.*;
    public class ClientGame {
         String ipAddress;
         Socket clientSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ClientGame(String ipAddress) {
              this.ipAddress = ipAddress;
              try {
                   System.out.println("Connecting To Host");
                 clientSocket = new Socket(InetAddress.getByName(ipAddress),4444);
                System.out.println("Host Found ...Io initializaton");
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
         public Object getData(){
              Object fromServer = null ;
              do{
                 try {
                      fromServer = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromServer==null);
              return fromServer;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                             out.writeObject(obj);
                        catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
              catch (IOException e){}
    public class ServerGame {
         ServerSocket serverSocket;
         Socket clientSocket;
         ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ServerGame() {
              try{
                   serverSocket = new ServerSocket(4444);
                   clientSocket = serverSocket.accept();
                   out =  new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
              catch(IOException e){System.out.println("IOException in ServerGame");}
         public Object getData(){
              Object fromClient = null ;
              do{
                 try {
                      fromClient = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromClient==null);
             return fromClient;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                   out.writeObject(obj);
              catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
                   serverSocket.close();
              catch (IOException e){}
         public static void main(String[] args) {
              new ServerGame();
    import java.io.Serializable;
    * this is a test object
    * it has a String field and a value
    *  The string is always the same but the integer value is defined in the constructor
    public class MyObject implements Serializable{
         private static final long serialVersionUID = 1L;
         String str;
         int myInt;
         MyObject(int a){
              str = "A String";
              myInt = a;
         public int getInt(){
              return myInt;
    }

    Pitelk wrote:
    I believe that a good code example can teach you things ;that you would need many days of searching; in no timeSo lets write one small example.. Ill help a little, but you do most of the work.
    jverd approach is deffenetly the way to go.
    jverd wrote:
    * Write a very small, simple Swing program with an input area, an output area, and a button. When you click the button, what's in the input area gets copied over to the output area.This part is partially done.
    * Write a very small, simple client/server program without Swing. It should just send a couple of hardcoded messages back and forth.And this part is for you(Pitelk) to continue on. I cannot say that this is the best way. or that its good in any way. I do however like to write my client/server programs like this. And perhaps, and hopefully, Ill learn something new from this as well.
    This is how far I got in about 10-20min..
    package client;
    * To be added;
    * A connect method. That connects the client to the server and
    * opens up both the receive and transmit streams. After doing that
    * the an instance of the ServerListener class should be made.
    * Also an disconnect method could be usable. But thats a later part.
    public class TestClass1 {
    package utils;
    import java.io.ObjectInputStream;
    import client.TestClass1;
    * This class is meant to be listening to all responses given from
    * the server to the client. After a have received data from the
    * server. It should be forwarded to the client, in this case
    * TestClass1.
    public class ServerListener implements Runnable {
         public ServerListener(ObjectInputStream in, TestClass1 tc) {
         @Override
         public void run() {
              while(true) {
    package server;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    * This class should handle all data sent to the server from the clients.
    class Server implements Runnable {
         private static List<ObjectOutputStream> outStreams = new ArrayList<ObjectOutputStream>();
         private Socket client = null;
         public Server(Socket client) {
              this.client = client;
         @Override
         public void run() {
              while(true) {
    * The meaning of this class is to listen for clients trying to connect
    * to the server. Once connection is achieved a new thread for that client
    * should be made to listen for data sent by the client to the server.
    public class ChatServer implements Runnable {
         @Override
         public void run() {
              while(true) {
    package utils;
    import java.io.Serializable;
    @SuppressWarnings("serial")
    public class MyObject implements Serializable {
         private String mssg;
         private String clientID;
         private String clientName;
         public MyObject(String mssg, String clientID, String clientName) {
              this.mssg = mssg;
              this.clientID = clientID;
              this.clientName = clientName;
         //Generate getters and setters..
    }Continue on this, and when you get into problems etc post them. Also show with a small regular basis how far you have gotten with each class or it might be seen as you have lost intresst and then this thread is dead.
    EDIT: I should probably also say that Im not more than a java novice, at the verry most. So I cannot guarantee that I alone will be able to solve all the problems that might occure during this. But Im gonna try and help with the future problems that may(most likely will) occure atleast(Trying to reserve my self incase of misserable failiure from me in this attempt).
    Edited by: prigas on Jul 7, 2008 1:47 AM

  • \\SERVER\Clients\Setup\setup.exe with Windows Vista Error

    I added the first Vista client to an SBS 2003, SP1 domain.  Until now, all clients were WinXP, SP2.  Office 2003 is installed on the XP clients, and the Vista client, which may not be pertinent to this problem.
    As is normal, "\\SERVER\Clients\Setup\setup.exe /s SERVER" is executed when a user logs on to any domain client.  On the Vista client, I always get the dialog -- regardless of the account privilege -- asking for permission to run Setup.exe.  It is annoying.  Occasionally, the Program Compatiblity Assistant will appear and advise there's a known compatiblity issue with Setup.exe.  It points to KB article 926505 for resolution.  The title of the KB is, "Windows Small Business Server 2003: Windows Vista and Outlook 2007 compatibility update."
    When I run the SBS2003SP1-KB926505-X86-ENU.EXE fix, I get the error:  "This update cannot be installed.  Either it is already installed as part of an existing service pack, or it requires a more recent service pack.  For more information, see the systems requirements on the download page."
    I installed Windows Server 2003 SP2 and run the KB926505 fix, but I get the same error  "This update cannot be installed.  Either it is already installed as part of an existing service pack" After a reboot of te SBS server the same  problem on the Vista client, I always get the dialog -- regardless of the account privilege -- asking for permission to run Setup.exe.  It is annoying.  Occasionally, the Program Compatiblity Assistant will appear and advise there's a known compatiblity issue with Setup.exe.  It points to KB article 926505 for resolution.
    The problem is Windows Vista Business, because all windows XP clients have no problem at all.

    PNP,
    You do not say whether if you accept the permission dialog whether the setup continues or not, but the short answer to the question revolves around UAC.
    Remember that EVERY user (except the actual Administrator account) has only Standard user rights regardless of group.  When a task that requires Admin rights is executed, one of three things will happen: 1) If you are THE Administrator, then your task will continue.  2) If you have Admin rights, you will be prompted that a process is trying to use elevated rights and ask for permission, or 3) If you are a Standard user, you will either be denied flatly or prompted to supply credentials.  Which of these happen depend on GPO settings, but the default is to prompt.
    In any event, I believe that this is what you are running into, and is one of the big feature improvements in Vista.  Yes, it can be a bit annoying (Try deleting an "All Users" icon from the Start Menu!) but is there to place one more barrier between virus and malware writers and your OS.
    If it's TOO annoying to bear, you can turn off UAC by going into your profile and disabling it. (It requires Admin rights, of course. )  It is not recommended as you do a very effective job or nutering the Vista Security Model by doing so.
    If it, of course, your choice.  we IT Admins have a lot more issues with this than the standard user, but for me, I gladly take the tradeoff because I worry a lot less about those few I HAVE to give Admin rights to.
    Good luck!

  • Regarding mountain lion server: clients experience intermittent service connections. the server system log has the following error- Client handshake failed (6):113: Server not accepting client connections (any ideas???)

    regarding mountain lion server: clients experience intermittent service connections. the server system log has the following error- Client handshake failed (6):113: Server not accepting client connections. any suggestions would be greatly appreciated - thank you

    Hi Jason
    I was getting the same behavior after Apple support had me delete some plist files to get Airplay going. I was also getting the following error:
    the error occurred while processing a command of type 'writesettings' in the plug-in 'server vpn'
    I went into ~/Library/Preferences/ and /Library/Preferences/ and deleted every plist contating the word server. I had to re-set up my server (meaning walk through some intial steps) but all of my settings were still there after that and everything started working again.
    Just a thought, obviously try at your own risk but it worked for me.
    Kellen

  • O.S. / Hard Drive Size for NIO Server/Client's load testing...

    Hi All
    I am currently load testing a NIO Server/Client's to see what would be the maximum number of connections that could reached, using the following PC: P4, 3GHz, 1GB RAM, Windows XP, SP2, 110 GB Hard Drive.
    However, I would like to test the Server/Client performance on different OS's:
    Which would be the best possible option from the following:
    1. Partition my current drive, (using e.g. Partition Magic), to e.g.
    - Win XP: 90 GB
    - Win Server 2000: 10 GB
    - Linux: 5 GB
    - Shared/Data: 5 GB
    2. Install a separate Hard drive with the different hard drives
    3. Use a disk caddie, to swap in/out test hard drives.
    4. Any thing else?
    - Would the Operating System's hard drive size affect the Server/Client's performance, e.g. affecting the number of connections, number of File Handles, the virtual memory, etc.?
    Many Thanks,
    Matt

    You can use a partition on the same HDD or use a second HDD, disk caddie well if its a direct IDE or SCSI. If its usb no it will be too slow, may be if you have a fire-wire but I still don't recommend it.
    Be careful if you don't have any experience installing Linux you may do multiple partitions on you disk without knowing, because Linux ext partitions are not visible to windows.
    Recommended disk size for fedora is 10 GB. This is the amount of data that will be created on you HDD when you do a full installation.

  • Java Server/Client Applicaton - problem with sending data back

    Hello!
    I'm trying to write a small server/client chat application in Java. It's server with availability to accept connections from many clients and it's app just for fun... However, I've come up against a huge problem: everything what clients send, arrives to server (I'm sure about that because it is displayed on the Server Application screen) and then server should send it back to all clients but it doesn't work. I have no faintest idea what causes this problem. Maybe you can help me?
    Here is my server app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Server {
        ServerSocket serw = null;
        Socket socket = null;
        String line = null;
        Vector<ClientThread> Watki = new Vector();
        ClientThread watek = null;
        public Server(int port) {
            try {
                serw = new ServerSocket(port);           
                line = "";
                while(true) {
                    System.out.println("Running. Waiting for client to connect...");
                    socket = serw.accept();
                    System.out.println("Connected with:\n" + socket.getInetAddress() + "\n");
                    watek = new ClientThread(socket);
                    Watki.addElement(watek);
                    Watki.firstElement().Send("doszlo?");
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void sendToAll(String s) {
            for(int i = 0; i < Watki.size(); i++) {
                Watki.elementAt(i).Send(s);
        public class ClientThread extends Thread {
            Socket socket;
            DataInputStream in = null;
            DataOutputStream out = null;
            String line = null;
            public ClientThread(Socket s) {
                try {
                    this.socket = s;
                    in = new DataInputStream(s.getInputStream());
                    out = new DataOutputStream(s.getOutputStream());
                    start();
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void Send(String s) {
                try {
                    out.writeUTF(s);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void run() {
                try {
                    line = "";
                    while (true) {
                        line = in.readUTF();
                        System.out.println(line);
                        sendToAll(line);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Server serwer = new Server(5000);
    }And here is client app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Client implements Runnable {
        Socket socket = null;
        BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
        DataInputStream in = null;
        DataOutputStream out = null;
        String line = null;
        public Client(String host, int port) {
            try {
                System.out.println("Connecting to " + host + ":" + port);
                socket = new Socket(host, port);
                System.out.println("Connected\nTALK:");
                out = new DataOutputStream(socket.getOutputStream());
                in = new DataInputStream(socket.getInputStream());
                line = "";
                while(!line.toLowerCase().equals(".bye")) {
                    line = keyIn.readLine();
                    Send(line);
            }catch (UnknownHostException e) {
                System.out.println("BLAD: " + e);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void Send(String s) {
            try {
                out.writeUTF(s);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void run() {
            String loaded = "";
            try {
                while(true) {
                    loaded = in.readUTF();
                    System.out.println(loaded);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Client client = new Client("localhost", 5000);
    }By the way, this app is mainly written in English language (text that appears on the screen) however in functions I used Polish language (for example: BLAD - it means ERROR in English). Sorry for that :)

    Yeap, I will change those exceptions later, thanks for advice.
    You asked what's going on with it: both applications start with no errors, but when I write something in client side it should be sent to the server and then forwarded to all connected clients but it stops somewhere. However, I added a one line to the server code
    line = in.readUTF();
    System.out.println(line);
    sendToAll(line); and after it reads message from client (no matter which one) it shows that message on the server side screen, then it should send this message to all clients but it doesn't work in this moment. What's confusing: no errors occurs, so it's rather a mistake in my code, but where?
    Edited by: Robin3D on Sep 30, 2009 9:07 AM

  • JMS Internal Error at Server Client Adapter!JMS Service is not started

    Hi
    Can any one tell me how to trouble shoot for following errors:
    Failed to Create Connection! Reason: Response from the server could not be reached.
    JMS Internal Error at Server Client Adapter!JMS Service is not started
    The following hosts could not be reached 143:223:221:10:50310
    We are trying to send the request from SONICMQ JMS to R/3 and trying to post the response to Sonic Queue. but we are facing some problems for JMS adapter .
    but in JMS sender and receiver adapter i gave different IP and port for listen the SONIC queue. why it is showing in different IP here? this message got from logviewer.
    regards
    Rambarki...

    Rambarki,
    What is the error displayed on the Adapter Monitoring pages?
    Generally the correct error descriptions for connectivity issues are found on adapter monitoring UI than any other.
    Other possible reasons could be :
    <i>JMS Service is not started
    The following hosts could not be reached 143:223:221:10:50310</i> This might be issue with your network settings i.e. XI server is unable to reach the specified IP on specified port.
    Regards,
    Amol

  • Non-blocking Server/Client is blocking...?!

    First, a simple question:
    Why in most example code using Selectors, when iterating over the Set returned by Selector.selectedKeys() does the currently selected SelectionKey get removed from the Iterator? I see it all the time, but since the SelectionKey is still bound to the underlying Selector it seems to not really do anything.
    Now to my main problem:
    I been working with 1.4 for a week now trying to implement a simple test server/client, whereby the server constantly sends out the current time to any subscribing clients, who in turn display the time to stdout. Pretty straight forward, huh?
    Well, everything seems to go fine...once. The Server accepts the client connection, sends out a the current time, the client (only one for now) receives it, displays to the screen, but then both server and client block on the Selector.select() method.
    If I shut down the client, the server then continues through the select() method, finding one SelectionKey, tries to write to it and throws an IOException (since the client is no more). I'm catching that exception and then removing the channel from the Selector, so that the server may continue to service requests.
    When starting a second client while the first is still running causes the following sequence of events:
    Server: starts up
    ClientA: connects to server
    Server: broadcasts the time
    ClientA: displays time
    // nothing else happens until...
    ClientB: connects to server
    Server: broadcasts the time
    ClientA: displays time
    ClientB: displays time
    //everything blocks again...
    ClientA: disconnects from server
    Server: broadcasts the time
    ClientB: displays time
    As you can see it seems everything blocks until a client does something (connect/disconnect).
    I will post code if anyone asks, but I don't want to spam the board if no one is willing to help me.
    -Justin

    You got it!
    //   ********** SERVER **********
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.CancelledKeyException;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Set;
    public class TestServer
      private static final int DEFAULT_PORT = 9999;
      public static void main(String[] args)
        TestServer s = new TestServer();
      }//end of main(String[])
      public TestServer()
        this(DEFAULT_PORT);
      }// end of TestServer()
      public TestServer(int port)
        InetSocketAddress addr = new InetSocketAddress(port);
        try
          Selector acceptSelector = Selector.open();
          Selector broadcastSelector = Selector.open();
          ConnectionList connections = new ConnectionList(broadcastSelector);
          Acceptor a = new Acceptor(acceptSelector, addr, connections);
          Broadcaster b = new Broadcaster(broadcastSelector, connections);
          a.start();
          b.start();
        }// end of try
        catch (Exception ex)
          ex.printStackTrace();
        }// end of catch
      }// end of TestServer(int)
      private static String status(Selector s)
        StringBuffer sb = new StringBuffer(100);
        sb.append("Selector: ");
        Set keys = s.keys();
        sb.append("\n\tNum Keys: ");
        sb.append(keys.size());
        Iterator iter = keys.iterator();
        int i = 0;
        while (iter.hasNext())
          try
            sb.append("\n\t[");
            sb.append(i++);
            sb.append("]:");
            SelectionKey key = (SelectionKey)iter.next();
            sb.append(" acceptable=");
            sb.append(key.isAcceptable());
            sb.append(" connectable=");
            sb.append(key.isConnectable());
            sb.append(" readable=");
            sb.append(key.isReadable());
            sb.append(" writable=");
            sb.append(key.isWritable());
          }// end of try
          catch (CancelledKeyException cke)
            sb.append("*** CANCELLED KEY");
          }// end of catch
        }// end of while
        return sb.toString();
      }// end of status(Selector)
      class Broadcaster extends Thread
        private final String TF = Broadcaster.class.getName();
        private int BUFFER_SIZE = 2048;
        private Selector selector_;
        private ConnectionList connections_;
        private ByteBuffer buffer_;
        public Broadcaster(Selector selector, ConnectionList connections)
          super("Broadcaster");
          selector_ = selector;
          connections_ = connections;
          buffer_ = ByteBuffer.allocateDirect(BUFFER_SIZE);
        public void run()
          while (true)
            try
              registerNewChannels();
              System.out.println("BroadcasterThread: Before select() "+status(selector_));
              System.out.println("BroadcasterThread: Selecting...");
              int keysReady = selector_.select();
              System.out.println("BroadcasterThread: After select() "+status(selector_));
              System.out.println("BroadcasterThread: "+keysReady+" ready Key(s)");
              if (keysReady > 0)
                transmit();
              }// end of if
            }// end of try
            catch (Exception ex)
              ex.printStackTrace();
              return;
            }// end of catch
          }// end of while
        protected void registerNewChannels()
        throws Exception
          SocketChannel channel = null;
          while (null != (channel = connections_.removeFirst()))
            channel.configureBlocking(false);
            channel.register(selector_, SelectionKey.OP_WRITE);
            System.out.println("BroadcasterThread: Registered connection from " + channel.socket().getInetAddress());
          }// end of while 
        }// end of registerNewChannels()
        public void transmit()
        throws Exception
          Set readyKeys = selector_.selectedKeys();
          System.out.println("BroadcasterThread: Selected Keys: "+readyKeys.size());
          SelectionKey tempKey = null;
          SocketChannel tempChannel = null;
          fillBuffer();
          for (Iterator i = readyKeys.iterator(); i.hasNext(); )
            tempKey = (SelectionKey)i.next();
            tempChannel = (SocketChannel)tempKey.channel();
            if (tempKey.isWritable())
              System.out.println("BroadcasterThread: Key selected is Writable");
              try
                tempChannel.write(buffer_);
                System.out.println("BroadcasterThread: Sent message to "+tempChannel.socket().getInetAddress());
              }// end of try
              catch (IOException ioe)
                System.err.println("BroadcasterThread: Lost Connection");
                tempChannel.close();
              }// end of catch
            }// end of if
            else
              System.out.println("BroadcasterThread: Key selected is not Writable");
            }// end of else
          }// end of for
          buffer_.clear();
        }// end of transmit()
        private void fillBuffer()
          buffer_.clear();
          /* Place Date in Buffer */
          long time = System.currentTimeMillis();
          Date d = new Date(time);
          System.out.println("BroadcasterThread: Broadcasting "+d);
          String date = d.toString()+"\n";
          byte[] datebuff = date.getBytes();
          buffer_.put(datebuff);
          /* Prepare for read operations */
          buffer_.flip();
        }// end of fillBuffer()
      }//end of inner class Broadcaster
      class Acceptor extends Thread
        private Selector selector_;
        private ConnectionList connList_;
        private final String TF = Acceptor.class.getName();
        public Acceptor(Selector selector, InetSocketAddress address, ConnectionList connList)
          super("Acceptor");
          selector_ = selector;
          connList_ = connList;
          try
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.socket().bind(address);
            System.out.println("AcceptorThread: Bound to " + address);
            ssc.register(selector_, SelectionKey.OP_ACCEPT);
          }// end of try
          catch (Exception ex)
            ex.printStackTrace();
          }// end of catch
        public void run()
          while (true)
            try
              System.out.println("AcceptorThread: Selecting...");
              int keysReady = selector_.select();// block till a channel is ready
              System.out.println("AcceptorThread: "+keysReady+" Keys Ready");
              if (keysReady > 0)
                acceptPendingConnections();
              }// end of if
            catch (Exception ex)
              ex.printStackTrace();
        protected void acceptPendingConnections()
        throws Exception
          Set readyKeys = selector_.selectedKeys();
          System.out.println("AcceptorThread: Selected "+readyKeys.size()+" Keys");
          for (Iterator i = readyKeys.iterator(); i.hasNext(); )
            SelectionKey key = (SelectionKey)i.next();
            i.remove();  
            ServerSocketChannel readyChannel = (ServerSocketChannel)key.channel();
            SocketChannel incomingChannel = readyChannel.accept();
            System.out.println("AcceptorThread: Connection from " + incomingChannel.socket().getInetAddress());
            connList_.add(incomingChannel);
          }// end of for
        }// end of acceptPendingConnections()
      }// end of inner class Acceptor
      class ConnectionList
        private LinkedList list_;
        private Selector selectorToNotify_;
        public ConnectionList(Selector toNotify)
          list_ = new LinkedList();
          selectorToNotify_ = toNotify;
        }// end of ConnectionList(Selector)
        public synchronized void add(SocketChannel newlyConnectedChannel)
          list_.add(newlyConnectedChannel);
          selectorToNotify_.wakeup();
        }// end of add(SocketChannel)
        public synchronized SocketChannel removeFirst()
          SocketChannel first = null;
          if (list_.size() > 0)
            first = (SocketChannel)list_.removeFirst();
          }//end of if
          return first;
        }// end of removeFirst()
      }// end of inner class ConnectionList
    }// end of class TestServer
    //   ********** CLIENT **********
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.CancelledKeyException;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.WritableByteChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class TestClient
      public static final String TF = TestClient.class.getName();
      private static final String DEFAULT_SERVER_IP = "127.0.0.1";
      private static final int DEFAULT_SERVER_PORT = 9999;
      private InetSocketAddress serverAddr_; 
      private Selector connectSelector_;
      private Selector readSelector_; 
      private WritableByteChannel outputChannel_; 
      private ByteBuffer receiveBuffer_;
      private SocketChannel serverChannel_;
      public static void main(String[] args)
        TestClient c = new TestClient();
      }// end of main(String[])
      public TestClient()
        this(DEFAULT_SERVER_IP, DEFAULT_SERVER_PORT);
      }// end of TestClient()
      public TestClient(String ip, int port)
        try
          serverAddr_ = new InetSocketAddress(ip, port);
          connectSelector_ = Selector.open();
          readSelector_ = Selector.open();
          outputChannel_ = Channels.newChannel(System.out);
          receiveBuffer_ = ByteBuffer.allocateDirect(512);
          connect();
          run();
        }// end of try
        catch (Exception ex)
          ex.printStackTrace();
        }// end of catch
      }// end of TestClient(String, int)
      private void connect()
      throws Exception
        serverChannel_ = SocketChannel.open();
        serverChannel_.configureBlocking(false);
        serverChannel_.connect(serverAddr_);
        serverChannel_.register(connectSelector_, SelectionKey.OP_CONNECT);
        int numKeys = 0;
        while (numKeys <= 0)
          System.out.println("connect(): Selecting...");
          numKeys = connectSelector_.select();
          System.out.println("connect(): "+numKeys+" ready Key(s)");
          Set readyKeys = connectSelector_.selectedKeys();
          System.out.println("connect(): Selected Keys: "+readyKeys.size());
          if (numKeys > 0)
            SelectionKey tempKey = null;
            SocketChannel tempChannel = null;
            Iterator i = readyKeys.iterator();
            while (i.hasNext())
              tempKey = (SelectionKey)i.next(); 
              i.remove();  
              tempChannel = (SocketChannel)tempKey.channel();
              if (tempKey.isConnectable())
                System.out.println("connect(): Key selected is Connectable");
                if (tempChannel.isConnectionPending())
                  System.out.println("connect(): Connection Pending");
                  tempChannel.finishConnect();
                  System.out.println("connect(): Connection Completed");
                }// end of if
              }// end of if
              else
                System.out.println("connect(): Key selected is not Connectable");
              }// end of else
            }// end of while
          }// end of if
        }// end of while
      }// end of connect()
      private void run()
      throws Exception
        serverChannel_.register(readSelector_, SelectionKey.OP_READ);
        while (true)
          System.out.println("run(): Before select() "+status(readSelector_));
          System.out.println("run(): Selecting...");
          int numKeys = readSelector_.select();
          System.out.println("run(): After select() "+status(readSelector_));
          System.out.println("run(): "+numKeys+" Ready Key(s)");
          if (numKeys > 0)
            processKeys();
          }// end of if
        }// end of while
      }// end of run()
      private void processKeys()
      throws Exception
        Set readyKeys = readSelector_.selectedKeys();
        System.out.println("processKeys(): Selected Keys: "+readyKeys.size());
        SelectionKey tempKey = null;
        SocketChannel tempChannel = null;
        for (Iterator i = readyKeys.iterator(); i.hasNext(); )
          tempKey = (SelectionKey)i.next();
          tempChannel = (SocketChannel)tempKey.channel();
          if (tempKey.isReadable())
            System.out.println("processKeys(): Key selected is Readable");
            try
              tempChannel.read(receiveBuffer_);
              receiveBuffer_.flip();
              outputChannel_.write(receiveBuffer_);
              receiveBuffer_.clear();
            }// end of try
            catch (IOException ioe)
              System.out.println("processKeys(): Lost Connection");
              tempKey.cancel();
            }// end of catch
          }// end of if
          else
            System.out.println("processKeys(): Key selected is not Readable");
          }// end of else
        }// end of for
      }// end of processKeys()
      private static String status(Selector s)
        StringBuffer sb = new StringBuffer(100);
        sb.append("Selector: ");
        Set keys = s.keys();
        sb.append("\n\tNum Keys: ");
        sb.append(keys.size());
        Iterator iter = keys.iterator();
        int i = 0;
        while (iter.hasNext())
          try
            sb.append("\n\t[");
            sb.append(i++);
            sb.append("]:");
            SelectionKey key = (SelectionKey)iter.next();
            sb.append(" acceptable=");
            sb.append(key.isAcceptable());
            sb.append(" connectable=");
            sb.append(key.isConnectable());
            sb.append(" readable=");
            sb.append(key.isReadable());
            sb.append(" writable=");
            sb.append(key.isWritable());
          }// end of try
          catch (CancelledKeyException cke)
            sb.append("*** CANCELLED KEY");
          }// end of catch
        }// end of while
        return sb.toString();
      }// end of status(Selector)
    }// end of class TestClient

  • After installing Final cut server client on OSX 10.6.8 error: Apple QuickTime or the QuickTime Java component is not installed.

    After installing Final cut server client on OSX 10.6.8 error: Apple QuickTime or the QuickTime Java component is not installed.
    I know this error on windows machines but cannot get a solution for OSX.

    I have fixed this by installing the latest combo update

  • Uncaught exception raised in Server Client-side plugin

    When I try to connect to my XServe from the Server Admin on my desktop computer. I get the following error:
    Uncaught exception raised in Server Client-side plugin
    Sorry but the feature you tried to access cannot be used. Exception is:
    In updateConfigurationViewFromDescription: NSInvalidArgumentException * -[NSCFNumber count]: unrecognized selector sent to instance 0x18819ee0 .
    There is a second error with similar wording.
    If I say ok to the warnings I can make changes but they do not save.
    I can access the Server Admin on the XServe
    Anyone know of a solution so that I can login and edit the settings for my XServe from a remote computer?

    I'm getting this too, server is XServe running 10.6.6, remote Server Admin is on a 10.5.8 PPC iMac. No errors with same remote against a PowerMac server running 10.5.8. No errors with 10.6.6 remote against either server.
    Unlike the OP, however, the changes I've tried "take." The pop-ups are annoying though.
    Another issue with the 10.5 Server Admin/10.6 Server, if it isn't a thread hijack, disk volumes do not show up in the File Sharing pane, Share Points appear OK.

  • Python Server/Client Application Development

    Hey All!
    I am writing a basic proof of concept server/client application for a project I am working on.
    My goal is this:
    1) End user launches client.
    2) Client connects to server.
    3) User selects one or more files to send to server.
    4) Server saves a copy of each file.
    5) Server terminates connection.
    5) Server processes each file.
    6) Upon completion of the processing server sets a "processing completed flag."
    7) Client periodically checks with server for "processing completed flag."
    8) Client securely reconnects
    9) Client downloads processed files.
    I have no background in programming servers/clients so this will be a learning experience for me and the workflow described above may change as I learn more about how this all works. Currently my hope is to first implement a system that will stay connected while the files are processed and once I have a better understanding as to how that works I can add more complexity to the system.
    I will be writing this in Python 3.3 and the server will be hosted on a server which will (for now) be running Arch.
    This thread will act as a sort of development journal but feel free to comment or post suggestions. I will for sure have questions as I go along too!

    brettski wrote:Turns out the best way (so far as I can tell) is to go integer -> string -> byte and then byte -> string -> integer..
    Do you mean regular, non-byte strings? That cannot possibly be the best way to do it. It would be like using Russian as an intermediary language for translating Spanish to French.
    Maybe the following will set you on the right path:
    http://stackoverflow.com/questions/6187 … -in-python
    http://stackoverflow.com/questions/4445 … int-python
    Looking further, this is probably the right way to do it:
    some_int = 57
    bytes = struct.pack('i', bytes)
    sock.send(bytes)
    See http://docs.python.org/3/library/struct.html for details.
    As for threaded servers, you may find some useful examples here.

  • Leopard Software Update Server + Client

    Hello,
    Now I have to use Mac OS X Tiger Server Software Update Server and OSX Tiger Client.
    After installing OS X Tiger Server software update, I turned on the server and on apdaty do I download and have been prepared. OS X Tiger has found his client software update server, and everything worked.
    Now I have OS X Leopard and Leopard Server Client.
    Purely installed server and client purely installed. The server is running the server software update is downloaded updates. Leopard Client still download updates from the Internet and not from the local network and I do not know where the error. Why in the older version of all work without interference with the terminal and not now? Can someone please help me set the software update server to the client computers may not have anything set up and found this site automatically.
    Thank you
    I apologize for my incorrect English

    The Tiger systems must have some form of customization. SWU is not an auto-discover service. If you have one of the Tiger systems still available, enter both of these commands and report the results:
    defaults read /Library/Preferences/com.apple.SoftwareUpdate
    defaults read /Users/<adminusername>/Library/Preferences/com.apple.SoftwareUpdate
    Does either of the results return the custom CatalogURL value? If not, then look in NetInfo Manager and look at your MCX values. There may have been a managed preference set for all systems. However, if Tiger systems are not bound that this is not possible unless an niutil command was run to insert the value.
    Also, keep in mind that if your Leopard systems are not bound to OD, and you have Apple Remote Desktop, you can use a Send Unix command and hit all of your systems in a matter of seconds. It is really rather trivial.
    Also, were your Tiger machines imaged from a DMG or a NetInstall Server? It is possible that the SWU custom address was set in the master image. This is why it appears to "just work."

  • UDP Server/Client Question

    Hi All,
    I'm just starting to work on this new server/client app and very new to UDP. Right now, I'm trying to read up on it. I'm wondering if anyone can point me to some good reading material. Quick question though, if a server (c-based) sends several messages, one right after another, can a client (java-based) handles these messages? I don't have any code to post just yet, still in the designing part. Thanks!

    Go for, JSP and Servlet ( Sun Microsystems )
    or Professional Java Server Programming wrox

  • Server/client application

    i'm just starting to learn about server/client applications and i'm a little confused about actually implementing them.
    my client will be an applet which can be accessed over the internet. i want the applet to be able to read/write to the server.
    now my question is, how can i start up the server program?
    i would want it to initialize and run, only when the user has gone to the website that uses the applet.

    look at using a Servlet, running under Tomcat (download the Java Web Services Developer pack from java.sun.com
    here's what the servlet looks like:
    mport javax.servlet.*;
    import java.util.*;
    import java.net.*;
    public class ServletTest extends GenericServlet
    /** servlet is initialising */
    public void init()
    System.out.println("ServletTest initializing");
    /** servlet wascalled bt client */
    public void service(ServletRequest request,ServletResponse response)
    try
    byte[] data=new byte[100];
    ServletInputStream inputStream=request.getInputStream();
    int read=inputStream.read(data);
    String string=URLDecoder.decode(new String(data,0,read),"UTF-8");
    System.out.println("read "+read+" bytes: "+string);
    inputStream.close();
    ServletOutputStream outputStream=response.getOutputStream();
    Date date=new Date();
    outputStream.write(date.toString().getBytes());
    outputStream.close();
    catch(Exception ex)
    ex.printStackTrace();
    /** servlet is being destroyed */
    public void destroy()
    System.out.println("ServletTest terminating");
    here's what the client looks like:
    mport javax.servlet.*;
    import java.util.*;
    import java.net.*;
    public class ServletTest extends GenericServlet
    /** servlet is initialising */
    public void init()
    System.out.println("ServletTest initializing");
    /** servlet wascalled bt client */
    public void service(ServletRequest request,ServletResponse response)
    try
    byte[] data=new byte[100];
    ServletInputStream inputStream=request.getInputStream();
    int read=inputStream.read(data);
    String string=URLDecoder.decode(new String(data,0,read),"UTF-8");
    System.out.println("read "+read+" bytes: "+string);
    inputStream.close();
    ServletOutputStream outputStream=response.getOutputStream();
    Date date=new Date();
    outputStream.write(date.toString().getBytes());
    outputStream.close();
    catch(Exception ex)
    ex.printStackTrace();
    /** servlet is being destroyed */
    public void destroy()
    System.out.println("ServletTest terminating");

  • Forms metrics server & client

    Hi hussein/helios
    What does forms metrics server & client do? Is it for load balancing? How does it load balance?
    I have not touch this subject before.
    Thanks a lot,
    MsK

    Hi,
    Please see these docs.
    Is It Necessary To Run Forms Metrics Client/Server If Not Load Balancing? [ID 797521.1]
    How To De-activate Temporarily The Forms Metrics Server & Clients ? [ID 416349.1]
    Thanks,
    Hussein

Maybe you are looking for

  • New to FIOS

    Hi all, Just had FIOS installed yesterday and for the most part, I really like it.  I've been a DISH customer for over 10 years but the triple play package I was offered was too good to pass up, so I made the change.  I'll be reasding more in the fou

  • Some fonts have become tiny and pale blue

    Example: When I view my online banking, my personal information is presented in a tiny font, which is also too pale to read, pale blue. When I am ordering something online, the fill-in boxes and what I type in them are tiny and pale blue. When I shop

  • User exit PCPO0001-EXIT_RPCIPE00_002 not working

    We have activated User exit PCPO0001- EXIT_RPCIPE00_002, requirement was to set the line item text SGTXT of the subsequent Accounting document, but there seem to be no activity happening for it (assigned breakpoints in the exit codes but transaction

  • Invalid Content-Type with SAAJ

    I get the following exception when trying to send a SOAPMessage with an attachment. Sorry for the length of this post. Lots of info. com.sun.xml.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:application/x-www-form-urlencoded. Is this an erro

  • I already have a WiFi access point. Can I still use a time capsule?

    I already have a WiFi access point.  Reading about the Time Capsule, it appears that it is also an access point.  If so, ca I still use it in conjuction with my existing WiFi?