Problem reading object via sockets

Hi All
I've the following class which I initialize and sent to differnet clients:
public class ParameterDisplay  implements Serializable {
     public int current;
     public int[][][] deck = null;
     public int[][][] onTable;
     public String names[];
     public int human = -1;
     public int[] length;   
     public int[] tlength;     
     public int centerImg = -1;
     public ParameterDisplay() {}
}The problem is that when a client reads this object all information in deck is lost!!!!
The array names is ok
Any suggestions what is the problem here???
Thanks in advance
Luca

Hi
I've rewritten some code and the problem didn't occure this time??!!
Futhermore there is too much code to show here, also to many places where it might go wrong I think.
So what I will do now is, rebuild the program an keep an eye on the Socket part during the whole process!!
Luca
ps writing games isn't so easy as I expected :)

Similar Messages

  • Cannot send and read objects through sockets

    I have these 4 classes to send objects through sockets. Message and Respond classes are just for
    trials. I use their objects to send ıver the network. I do not get any compile time error or runtime error but
    the code just does not send the objects. I used object input and output streams to send and read objects
    in server (SOTServer) and in the client (SOTC) classes. When I execevute the server and client I can see
    that the clients can connect to the server but they cannot send any objects allthough I wrote them inside the main method of client class. This code stops in the run() method but I could not find out why it
    does do that. Run the program by creating 4 four classes.
    Message.java
    Respond.java
    SOTC.java
    SOTServer.java
    Then execute server and then one or more clients to see what is going on.
    Any ideas will be appreciated
    thanks.
    ASAP pls
    //***********************************Message class**********************
    import java.io.Serializable;
    public class Message implements Serializable
    private String chat;
    private int client;
    public Message(String s,int c)
    client=c;
    chat=s;
    public Message()
    client=0;
    chat="aaaaa";
    public int getClient()
    return client;
    public String getChat()
    return chat;
    //*******************************respond class*****************************
    import java.io.Serializable;
    public class Respond implements Serializable
    private int toClient;
    private String s;
    public Respond()
    public Respond(String s)
    this.s=s;
    public int gettoClient()
    return toClient;
    public String getMessage()
    return s;
    //***********************************SOTServer*********************
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    //private class
    class ClientWorker extends Thread
    private Socket client;
    private ObjectInputStream objectinputstream;
    private ObjectOutputStream objectoutputstream;
    private SOTServer server;
    ClientWorker(Socket socket, SOTServer ser)
    client = socket;
    server = ser;
    System.out.println ("new client connected");
    try
    objectinputstream=new ObjectInputStream(client.getInputStream());
    objectoutputstream=new ObjectOutputStream(client.getOutputStream());
    catch(Exception e){}
    public void sendToClient(Respond s)
    try
    objectoutputstream.writeObject(s);
    objectoutputstream.flush();
    catch(IOException e)
    e.printStackTrace();
    public void run()
    do
    Message fromClient;
    try
    fromClient =(Message) objectinputstream.readObject();
    System.out.println (fromClient.getChat());
    Respond r=new Respond();
    server.sendMessageToAllClients(r);
    System.out.println ("send all completed");
    catch(ClassNotFoundException e){e.printStackTrace();}
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    break;
    Respond k=new Respond();
    sendToClient(k);
    }while(true);
    public class SOTServer
    ServerSocket server;
    Vector clients;
    public static void main(String args[]) throws IOException
    SOTServer sotserver = new SOTServer();
    sotserver.listenSocket();
    SOTServer()
    clients = new Vector();
    System.out.println ("Server created");
    public void sendMessageToAllClients(Respond str)
    System.out.println ("sendToallclient");
    ClientWorker client;
    for (int i = 0; i < clients.size(); i++)
    client = (ClientWorker) (clients.elementAt(i));
    client.sendToClient(str);
    public void listenSocket()
    try
    System.out.println ("listening socket");
    server = new ServerSocket(4444, 6);
    catch(IOException ioexception)
    ioexception.printStackTrace();
    do
    try
    ClientWorker clientworker=new ClientWorker(server.accept(), this);
    clients.add(clientworker);
    clientworker.start();
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    while(true);
    protected void finalize()
    try
    server.close();
    catch(IOException ioexception)
    ioexception.printStackTrace();
    //*************************SOTC***(client class)*********************
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    class SOTC implements Runnable
    private Socket socket;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    public void start()
    try
    socket= new Socket("127.0.0.1",4444);
    input= new ObjectInputStream(socket.getInputStream());
    output= new ObjectOutputStream(socket.getOutputStream());
    catch(IOException e){e.printStackTrace();}
    Thread outputThread= new Thread(this);
    outputThread.start();
    public void run()
    try
    do
    Message m=new Message("sadfsa",0);
    output.writeObject(m);
    Respond fromServer=null;
    fromServer=(Respond)input.readObject();
    }while(true);
    catch(NullPointerException e){run();}
    catch(Exception e){e.printStackTrace();}
    public SOTC()
    start();
    public void sendMessage(Message re)
    try
    Message k=new Message("sdasd",0);
    output.writeObject(k);
    output.flush();
    catch(Exception ioexception)
    ioexception.printStackTrace();
    System.exit(-1);
    public static void main(String args[])
    SOTC sotclient = new SOTC();
    try
    System.out.println("client obje sonrasi main");
    Message re=new Message("client &#305;m ben mesaj bu da iste",0);
    sotclient.sendMessage(re);
    System.out.println ("client gonderdi mesaji");
    catch(Exception e) {e.printStackTrace();}

    ObjectStreams send a few bytes at construct time. The OutputStream writes a header and the InputStram reads them. The InputStream constrcutor will not return until oit reads that header. Your code is probably hanging in the InputStream constrcutor. (try and verify that by getting a thread dump)
    If that is your problem, tolution is easy, construct the OutputStreams first.

  • Problem reading objects

    Hi i am trying to read objects from i file i have written them to but cannot seem to get it goint any suggestions here are two errors but i am sure their are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must be positive.");
    }

    Hi i am trying to read objects from i file i have
    written them to but cannot seem to get it goint any
    suggestions here are two errors but i am sure their
    are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^I'm not sure what you're trying to do exactly, I think its retrieve the next object from ObjectInputStream, you'd probably want to use another variable of type Object
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal TerminationNo flush() for InputStream objects.
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights
    reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws
    ws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new
    r (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream
    Stream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream
    Stream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new
    Eater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException
    xception message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting
    ing NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the
    the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must
    st be positive.");

  • Problems Reading SSL  server socket  data stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
        int tag = public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag
        ...

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Problems starting tcode from swo1-object via gos (so_sendobj)

    Hi,
    working with gos around some swo1-object, i got the problem to start a transaction which is called from an object method: the transaction starts but the wished details of that item do not appear as expected.
    When I start the test environment within tcode SWO1, and at first, I create an instance from this object giving it the right key (for the wished item) then i succeed in starting the bespoken transaction from within that method showing me the details for that item.
    In the last days, I have read and learned a lot about the possibilities and interdependences of the gos mechanism using many of the hints and advices which were given here in the forum in the past. But I'am not able to achieve the wished effect via gos (send object with note) from within our application.
    My guess, we need to start an instance of the object before we can show details for the wished item. In the normal case, the application shows at the left windows with containers/trees for search filters and items and within the main window on the right the details for that item. Starting this transaction a popup-window appears (showing the standard filter) where you can give the wished item no.
    As I remarked, starting all these things from within the swo1 environment everything is functioning as expected...
    Is there anybody who has made a similar experience and can give me some advice what we have to do to succeed in?? Is there any function module of kind SWU..., SWE... SWO... or something else which is to be called in front of that task???
    I forgot to mention that within our application, there is the correct? built up of the gos-object via class cl_gos_manager constructing the needed object and the needed key, so when calling the gos-action, the bypassed sap user finds the link in the inbound position and will be directed to the correct transaction with the side effects described before.
    Wish you all together a happy new year.
    Kind regards
    Christian

    My freind  ,
    in the   Bussiness Objects  migatration there is  no select-options  like   
    sending  range of data  or the multiple selections.
    for this we need separate   loop structure   where in we can send the multiple   data  and everytime it calls the  BAPI Obect  evertime  individaully ,
    if you want the  you have to  define  one  new   BOR  object  (Custom bapi)...then  rignt  one  function module for   select-options and  attach it to  you method  in the BAPI   .
    So that   your  BAPI calls  in the SAP  function Module   for  range of data .
    Reward  points if it is  usefull ....
    Girish

  • Trying to read from a socket character by character

    Hi all,
    I have a problem with reading from a socket character by character. In the code shown below I try and read each character, and then write it to a file. The information sent to a socket sent from a file, and EOF is marked with character of ascii code 28 (file separator). However using BufferedReader.read() I get -1 forever. Is it reading only the last character to have been sent to the socket?
    As a side note, if I use readLine() (making sure the socket is sent a newline at end of msg) I can get the message fine. However, I want to be able to receive a message with 0 or many newlines in it (basically contents of a text file), so I want to avoid the readLine() method.
    Any help at all is appreciated,
    Colm
    CODE SNIPPET:
    try
    serverSocket = new ServerSocket(listenToPort);
    System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
    while(true)
    inSocket = serverSocket.accept();
    System.out.println("New connection accepted " + inSocket.getInetAddress() + ":" + inSocket.getPort());
    input = new BufferedReader(new InputStreamReader(inSocket.getInputStream()));
    fileOutput = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Ready to write to file: " + outputFilename);
    //receive each character and output it to file until file separator arrives
    while(!eof)
    inCharBuf = input.read();
    System.out.print(inCharBuf);
    //check for file separator (ASCII code 28)
    if (inCharBuf == 28) eof = true;
    //inChar = (char) inCharBuf;
    fileOutput.write(inCharBuf);
    System.out.println("Finished writing to file: " + outputFilename);
    inSocket.close();
    catch (IOException e)
    System.out.println("IO Error with serverSocket: " + e);
    System.exit(-1);
    }(tabbing removed as it was messing up formatting)

    My guess is that the code that is writing to the
    socket did not flush it. You said in one case you
    could read it (via readln) if the writer was writing
    lines (writeln flushes, I believe). Are you writing
    the exact same data to the socket in both tests?woo hoo, I hadn't flushed the buffers alright!
    for anyone with similar problems, I was missing this from my write-to-socket method:
    output.flush();
    where output was the BufferedWriter I had created to write to the socket.
    Thanks a lot for pointing it out!
    Colm

  • Server hangs up when tryin to read object Urgent Help Plz

    Hi,
    I've been working on a client-server model for a while, I've tested my applicaction a thousand of times locally (I mean, server and serveral clients running on the same machine) and it's ok, now I finally run server in a remote host and I find it rarely works fine, most of the times server hangs up when tryin to read objects I dont know why.
    this is the part of the server-code where the problem begins:
    public int EscucharSocket(){
            Socket cliente = null;
            System.out.println("Servidor en escucha...\n");
            while(true){
                try{
                    cliente = SocketS.accept();
                    //I get client's ip and port
                    String ip = cliente.getInetAddress().getHostAddress();
                    int puerto = cliente.getPort();
                    //After the conexion is made, server reads a signature to
                    //identify the client
                   //in function process I check if the signature is valid
                   //SignedData is a class where I wrap the signiture (obviously
                   //it implements Serializable interface
                   process((SignedData)le.LeerObject(cliente));
                   //Other things done here
                catch (Exception e) { }
    }le is a class I use to read,write data to the socket, this is the code of the LeerObject function
    public Object LeerObject(Socket c) throws Exception {
           //Here Is where the server hangs up
            ObjectInputStream b = new ObjectInputStream(c.getInputStream());
            return b.readObject();
    }As I wrote when running locally, there is no problem, but when I have a remote host, that happens
    Any help or idea?

    Hi again, thnx for your help
    I modified my LE class so I just create a couple of Input/Output Streams per client (on server n client program), this is now the complete code of the class:
    import java.net.*;
    import java.io.*;
    public class LE {
        DataOutputStream     dos;
        ObjectOutputStream  oos;
        DataInputStream        dis;
        ObjectInputStream     ois;
        //Streams are created just once in the constructor
        public LE (Socket s) throws Exception {
            dos = new DataOutputStream(s.getOutputStream());
             //I'm not sure if this flush has any sense
            dos.flush();
            oos = new ObjectOutputStream (s.getOutputStream());
            oos.flush();
            dis = new DataInputStream(s.getInputStream());
            ois = new ObjectInputStream (s.getInputStream());
        public void EscribirByte(byte datos[],int len) throws Exception {
            dos.write(datos,0,len);
            dos.flush();
        public void EscribirString(String dato) throws Exception {
            dos.writeUTF(dato);
            dos.flush();
        public void EscribirChar(char dato) throws Exception {
            dos.writeChar(dato);
            dos.flush();       
        public void EscribirInt(int dato) throws Exception {
            dos.writeInt(dato);
            dos.flush();
        public void EscribirLong(long dato) throws Exception {
            dos.writeLong(dato);
            dos.flush();
        public void EscribirObject(Object dato) throws Exception {
            oos.writeObject(dato);
            oos.flush();
        public String LeerString() throws Exception {       
            return dis.readUTF();
        public int LeerInt() throws Exception {       
            return dis.readInt();
        public char LeerChar() throws Exception {       
            return dis.readChar();
        public long LeerLong() throws Exception {       
            return dis.readLong();
        public Object LeerObject() throws Exception {       
            return ois.readObject();
    }part of code of server and client, where the conexion is made and the LE object is created
    Server:
    try{
           cliente = SocketS.accept();               
           //After accepting the conexion the LE object is created
            le = new LE(cliente);
            //I get client's ip and port
            String ip = cliente.getInetAddress().getHostAddress();
            int puerto = cliente.getPort();
            //Object wraping signature is read        
            process((SignedData)le.LeerObject());
            //other control operations doing here
            //A thread is created to receive requests from client
            //(reference to LE object is passed to the thread
           ConexionCliente c = new ConexionCliente (cliente,id_persona,id_grupo,tipo_usuario,backup,le);                               
            //thread is started
            c.start();
    catch (Exception e) {
        try {
            cliente.close();
        catch(Exception e2){}
    }Cliente code:
    try{
       //it connects to the server
       c=new Socket(host,puerto);
       //After accepting the conexion the LE object is created         
       le = new LE(c);
       //other things made here to genarate SignedData Object
      //It sends signed data object
      le.EscribirObject(Data);          
      //A thread is created and started to receive messages from server
      //reference to object LE is sent to the thread to avoid the need of
      //creating another
      new ConexionServidorClient(c,id_persona,ci,le).start();
      return 1;
    catch(Exception e) {
       return -1;
    }after the change, itworks a little better, but still most of the times server hangs up, I can't make server operational yet and I dont have any idea for solving this issue

  • Reading Objects using NIO

    I having problems reading an object using NIO APIs. I am end creating an Object and pass it through a socket. When I retrieve the data from the input stream within the socket I initialize a ByteBuffer by allocating a length. The problem is that there is NO way of knowing what to allocate that ByteBuffer when reading in the object. Below is within a method that allows me to read information from the socket.
    //Allocate the length ByteBuffer.
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //Read the data from the SocketChannel....PROBLEM IS WHAT IF I NEED TO DO MULTIPLE READS
    socketChannel.read(buffer);
    ///We will create a byte array from the ByteBuffer.
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client. *********SPECIAL Class that will cast our generic object into a Message Object.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    ----The problem is if I have more data within that Object. I need to re-allocate the ByteBuffer object and read everything on that socket. I tried the following code but I really don't feel it will be optimized the best for performance. I guess my question is that should I even be using NIO in this situation or Blocking IO?
    Again, here is the code that will read multiple data from the socket until it is -1.
    //Here we will read the information we received by first allocating
    //a ByteBuffer object.
    ByteBuffer buffer1 = ByteBuffer.allocate(5);
    ByteBuffer buffer2 = ByteBuffer.allocate(0);
    //We will read the data from this object.
    while ((socketChannel.read(buffer1)) != -1) {
    //We will check the Buffers and then try to recreate a new ByteBuffer that will put the remaining
    //stuff within the buffer. NOT SURE IF THIS IS THE MOST EFFICIENT WAY OF DOING THIS
    //AND ACTUALLY DON'T HAVE THE CODE WORKING CORRECTLY. THIS IS WHERE I
    //NEED HELP ON THE CORRECT WAY TO DO THIS.
         if (buffer1.remaining() < buffer2.remaining()) {
              buffer1.flip();
              buffer2 = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining());
              System.out.println("tmp 2 Remaining : " + buffer2.remaining());
              //tmp.put(buffer2);
              //buffer2 = tmp;
              System.out.println("Buffer 2 Remaining : " + buffer2.remaining());
         buffer2.put(buffer1);
         buffer1.clear();
    //We will create a byte array from the ByteBuffer.                    
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer2.clear();
    buffer1.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    Any help would be greatly appreciated.

    I use my own InputStream class overriding the two standard read functions read( byte[], index, length ) and read(). When you construct it pass in the channel you are reading from and read from the channel on demand. ie when a call to read comes in you read say 100 bytes from the channel. The call required only 80 so these are consumed and the other 20 are buffered. Another read call is made, this time for 50 bytes but we only have 20 buffered so another read of the channel is needed. It is up to you whether you break the contract of read( byte[], index, length ) to keep reading the channel until the full "length" is available, or handle this in your application code.
    Then because this class is InputStream you can wrap it up inside any stream you like such as the ObjectInputStream and the data will be serialized correctly.

  • Problem Reading mp3 fles on Mac OS X Snow Leopard

    Hi
    Am deploying an application to mac osx snow leopard. my application is suppose to accept files by drag drop / browse select. it supports mp3 files only. it is suppose to load mp3 files with sound object, and read the id3 data and populate in into data grid. it works fine on windows. mp3 loading does not work on mac. can some one please help. this is urgent. is there a issue with this for mac platform ?
    i basically pass audiofile.nativePath to sound object via new URLREQUEST.

    The problem with my application was due to few things that were wrong.
    1. Loading Mp3 files vis fileobject.nativePath is incorrect way to load such resources. you must use fileobject.url instead.
    2. Comparing for file type with logic such as :
    if((j.type.toLowerCase())== FILETYPE)
    will have issues on mac, because:
    The file type.
    In Windows or Linux, this property is the file extension. On the Macintosh, this property is the four-character file type, which is only used in Mac OS versions prior to Mac OS X. If the FileReference object was not populated, a call to get the value of this property returns null.
    3. I need to set sandbox as “file system” to access the content of audio resource.  The method is :”open FlexBuilder -> project -> Properties -> Flex Complier -> Additional Complier arguments -> add “-use-network=false” “.
    Now my application works cross platform. Thanks to a outstanding support by the Adobe Air Support.
    Especially: Michael

  • Passing Objects via Request

    I have a very simple problem that is bugging me to death. I've created a simple logon page that authenticates against an ldap directory. Once the authentication has completed successfully I create a user detail object which. Upon success the action returns success and I need to pass that UserDetails object to the forwarding page to display the data. What is the best method to do this? Thanks for the help guys.

    If you're forwarding from one view to another via navigation, then in the action that submits the form, store the object in the RequestMap or SessionMap:
    FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put(<name>,<object>);or
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(<name>,<object>);You can then refer to this object via the expression #{requestScope.name} where name was the value you used when storing in the map.

  • Getting RuntimeException while sending a JMenu Object via http

    Hello,
    since Java 1.5.0 i use a mechanism, which transfers a JMenu from my servlet object to my applet object via http.
    Now since 1.5.0_02 i get this Exception while doing it:
    java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.swing)
    Now there is nothing to find about this. Not here in the forums, neither in google or anywhere else.
    My guess is, its a matter of deserialization of thoses Jmenus.
    Anybody out there with the same problem?
    Anybody knows how to solve this WITHOUT changes the policy?
    thanks
    steffan

    The directory that contains msgsend.class (usually the current directory)
    is not in your CLASSPATH setting. Be sure that "." is included as one of the
    entries in CLASSPATH.

  • Visa read object difference parity setting for PC and TPC2012 device

    Hello,
     we found some difference between application running in PC and runing in TPC2012 device.
    We tested modbus communication via RS485 (9600b/s, 8bits, parity even) between PLC(master) and TPC2012 (slave). We used Visa read object and set parity to Even via property node. From the PLC we sent request to device and in our application we only read the data from PLC and displayed it (8bytes) on sreen.
    If we tested the application on PC everything worked fine. But if we compiled application and ran it in TPC2012 device  the data was different (for example if I sent request from PLC to slave 05 03 00 01 00 01 crc crc on the TCP I saw 00 03 00 01 00 01 crc crc. The  crc on TPC wasn't equal to crc on PLC.
    We found that problem was in VISA read setiing for read data in TPC device. If we set parity to SPACE (instead of EVEN)  then we read data correctly.
    Modbus - Parity set for VISA read object:
    Master PLC (even) - PC (even) -> visa read - data are equal
    Master PLC (even) - TPC (even) -> visa read - data aren't equal
    Master PLC (even) - TPC (space)-> visa read - data are equal 
    PC: Win XP SP2, LabView 8.5 with LabView TP module 8.5.
    TPC2012: WinCE 5.0, NI visa 4.2, NI TPC Service 1.0.
    Best regards,
    Pavel Rucka.

    I just found out that the VI for the currentmeasurement with the keithley 6517a has the same error but still works fine. Now I also tried to adjust the serial data bit and parity settings via the VISA configure serial port function but still no improvements.

  • How to get server data without reading from the socket stream?

    My socket client checks for server messages through
                while (isRunning) { //listen for server events
                    try {
                            Object o = readObject(socket); //wait for server message
                                tellListeners(socket, o);
                    } catch (Exception e) {
                        System.err.println("ERROR SocketClient: "+e);
                        e.printStackTrace();
                    try { sleep(1000); } catch (InterruptedException ie) { /* ignore */ }
                }//next client connectionwith readObject() being
        public Object readObject(Socket socket) throws ClassNotFoundException, IOException {
            Object result = null;
    System.out.println("readObject("+socket+") ...");
            if (socket != null && socket.isConnected()) {
    //            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectInputStream ois = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
                try {
                    result = ois.readObject();
                } finally {
    //                socket.shutdownInput(); //closing of ois also closes socket!
        //            try { ois.close(); } catch (IOException ioe) { /* ignore */ }
            return result;
        }//readObject()Why does ois.readObject() block? I get problems with this as the main while loop (above) calls readObject() as it's the only way to get server messages. But if i want to implement a synchronous call in adition to this asynchronous architecture (call listeners), the readObject() call of the synchronous method comes to late as readObject() call of the main loop got called before and therefore also gets the result of the (later) synchronous call.
    I tried fideling around with some state variables, but that's ugly and probably not thread safe. I'm looking for another solution to check messages from the server without reading data from the stream. is this possible?

    A quick fix:
    - Add a response code at the beginning of each message returned from the server indicating if the message is a synchronous response or a callback (asynch);
    - Read all messages returned from the server in one thread and copy callback messages in a calback message queue and the synch responses in an synch responses queue;
    - Modify your synchronous invocation to retrieve the response from the responses queue instead from the socket. Read the callback messages from the corresponding queue instead from the socket.
    Also take a look at my website. I'm implementing an upgraded version of this idea.
    Catalin Merfu
    High Performance Java Networking
    http://www.accendia.com

  • Not able to send euro character ' €' via socket

    OS : Solaris - The solaris login profile is set with LC_CTYPE, LC_CTYPE, LC_LANG=ISO-8859-15 and we are able to see this when we run the set command and also locale in solaris.
    JRE : 1.6
    Application deployed in Weblogic 10.3
    I m trying to send a euro character in java via socket, but in the receiving end not able to receive properly. Even I have to tried to set the Charset ( in the java code )
    as ISO-8859-15 , but still it didn't work properly. Code snippet for the sample program to display euro symbol
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.Charset;
    public class Euro {
    public static String createString( byte[] bytes, String enc )
    String CResult = null;
    try {
    CResult = new String( bytes, enc );
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return CResult;
    // ISO8859-15 is same as ISO8859-1 but with EUR character
    public static String createStringISO8859_15( byte[] bytes )
    String CResultISO = null;
    CResultISO = new String( bytes, Charset.forName("ISO-8859-15" ));
    return CResultISO;
    public static void main(String[] args) throws Exception {
    //String enc = "€";
    byte[] iso8859_15 = { (byte) 0xA4 }; // euro sign
    //byte[] iso8859_15 = "0xA4".getBytes(); // euro sign
    /*     String Cresult = Euro.createString (iso8859_15, enc);
    System.out.println("createString Result : " + Cresult);*/
    String CresultISO = Euro.createStringISO8859_15(iso8859_15);
    System.out.println("createStringISO8859_15 Result : " + CresultISO);
    When I 'm running the above code in windows it is working fine whereas in Solaris it is not working. The console just displays ?, rather than the actual '€' symbol. Is this a display problem in console of vt100 or porgramming? Kindly suggest. How to make this work in Solaris.

    Please repost or edit that mess with {noformat}{noformat} tags and proper indenting so it can actually be read.
    And then explain what sockets have to do with the price of fish.                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem reading attached PDF files

    <!--[if gte mso 9]><xml>
    </xml><![endif]--><!--[if gte mso 9]><xml>
    Normal
    0
    false
    false
    false
    MicrosoftInternetExplorer4
    </xml><![endif]--><!--[if gte mso 9]><xml>
    </xml><![endif]--><!--[if !mso]>
    <object
         classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui>
    </object>
    <style>
    st1\:*{behavior:url(#ieooui) }
    </style>
    <![endif]-->
    <!--[if gte mso 10]>
    <style>
    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-parent:"";
    mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
    mso-para-margin:0cm;
    mso-para-margin-bottom:.0001pt;
    mso-pagination:widow-orphan;
    font-size:10.0pt;
    font-family:"Times New Roman";
    mso-ansi-language:#0400;
    mso-fareast-language:#0400;
    mso-bidi-language:#0400;}
    </style>
    <![endif]-->
    Hello.
    At my work, we use JavaMail (version 1.4.1) in server
    programs, processing mails with attached files from customers. Mostly it is
    TIFF images, but it can also be PDF
    files, and the attached files are extracted and saved for further processing.
    Sometimes, we have a problem, reading attached PDF
    files. The files get saved, but is of size 0 bytes. If I forward it, however,
    using an Outlook client, the forwarded item can be read by our JavaMail program, and files saved OK.
    I have tried to forward it using JavaMail, but I cannot
    compose the mail parts, that fails, however - of the same reasons: I cannot
    read the them in:-)
    It looks like it's when the mail is send from a Mac.
    Anyway, the part to read is of content type "APPLICATION/APPLEFILE" whereas when it's forwarded, it's content
    type is "APPLICATION/OCTET-STREAM"
    The way, I read the part, is to check if the part is an
    instance of an InputStream, and then saving into a byte array, like this:
    h5. Object
    obj = part.getContent();
    if (obj instanceof
    InputStream) {
    InputStream
    inStream = part.getInputStream();
    byte[]
    buffer = new byte[BUFFER_SIZE];
    int
    bytesRead;
    BufferedOutputStream
    outBufStream = new BufferedOutputStream(new FileOutputStream(attFileName));
    while
    ((bytesRead = inStream.read(buffer)) != -1)
    outBufStream.write(buffer,
    0, bytesRead);
    inStream.close();
    h5. outBufStream.close();
    Problem
    is that .read() method always returns -1 when content type Is APPLICATION/APPLEFILE,
    so a file of 0 bytes are created.
    Interesting is perhaps, that debugging shows me that the
    part instance of the InputStream actually is a
    com.sun.mail.util.BASE64DecoderStream when it fails, and a
    com.sun.mail.util.QPDecoderStream
    when it works OK.
    So I have this idea, that I's a certain type of decoder
    stream we're missing? We use Java 1.6.0 update 10 and JavaMail 1.4.1. and since
    we use java 1.6 we use the JAF framework from that one, I guess?
    Hope you guys can help?
    Thanks in advance, Per Jensen
    [email protected]

    We have two (MS Exchange) servers (from trace log):
    Microsoft Exchange IMAP4rev1-server version 5.5.2650.23
    Microsoft Exchange Server 2003 IMAP4rev1 server version 6.5.7226.0
    - the first one is the one, we're using here, but I have tried on the other, newer version too, and it didn't help either.
    But I've found out a couple of interesting things:
    1: Debugging shows me, that the part instance of the InputStream actually is a com.sun.mail.util.BASE64DecoderStream when it fails, and if I forward the mail via Outlook as described earlier, and it can be read OK, the part is a com.sun.mail.util.QPDecoderStream instance.
    2: I can save the WHOLE message to a file, using message.getInputStream(), and when I opens the file I can find the individual attachments - as well as the bodytext, if any - as they are separated with the disposition, mimetype and filename fields, showed as plain text. And the attachments are showed as blocks of characters; I guess it's the ascii character representation of the bytes. Here's a snippet, note the first two sentences. They seemes to be added, somehow, when I dump the message to file(?):
    <START OF DUMPED FILE>
    This message is in MIME format. Since your mail reader does not understand
    this format, some or all of this message may not be legible.
    ------_=_NextPart_000_01C9A8A2.19479FE4
    Content-Type: text/plain;
         charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    (The body text here)
    ------_=_NextPart_000_01C9A8A2.19479FE4
    Content-Type: application/applefile;
         name="first_attachment.pdf"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
         filename="first_attachment.pdf"
    AAUWAAACAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAASgAAABAAAAAJAAAAWgAAACAAAAADAAAA
    egAAABAAAAABAAAAigAAI6IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAA1NzE2NSBCTkhhdWcucGRmJVBERi0xLjMKJbe+raoKMSAwIG9iago8PAovVHlwZSAv
    Q2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9L
    aWRzIFsgNCAwIFIgXQovQ291bnQgMQo+PgplbmRvYmoKMyAwIG9iago8PAovUHJvZHVjZXIgKEhh
    ...(and so on)
    DMgMDAwMDAgbg0KMDAwMDAwNTM1NSAwMDAwMCBuDQowMDAwMDA2NTA5IDAwMDAwIG4NCjAwMDAw
    MDc2NjUgMDAwMDAgbg0KdHJhaWxlcgo8PAovUm9vdCAxIDAgUgovSW5mbyAzIDAgUgovU2l6ZSAx
    MQo+PgpzdGFydHhyZWYKODgyNAolJUVPRgo=
    ------_=_NextPart_000_01C9A8A2.19479FE4
    Content-Type: application/applefile;
         name="second_attachment.pdf"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
         filename="second_attachment.pdf"
    AAUWAAACAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAASgAAABAAAAAJAAAAWgAAACAAAAADAAAA
    egAAABAAAAABAAAAigAAI9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAA1NzE4MSBCTkhhdWcucGRmJVBERi0xLjMKJbe+raoKMSAwIG9iago8PAovVHlwZSAv
    Q2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9L
    ...(and so on)
    <END OF DUMPED FILE>I understand that it's base64 encoded and must be decoded, and I have tried to copy/paste the blocks separately, run them through the com.sun.mail.util.BASE64DecoderStream, and saving them as PDF files, which works fine(!).
    As the solution seems to be painfull: Parse the mail to find where the attachments starts and stops and saving them as files, I hope you guys can send me on the right track?
    PS: The trace log when dumping the file shows everything OK, I think. Here's a bit of the log at the end of dumping the message:
    (...)MTUgMDAwMDAgbg0KMDAwMDAwNTg2NyAwMDAwMCBuDQowMDAwMDA3MDIxIDAwMDAwIG4NCjAwMDAw
    MDgxNzcgMDAwMDAgbg0KdHJhaWxlcgo8PAovUm9vdCAxIDAgUgovSW5mbyAzIDAgUgovU2l6ZSAx
    MQo+PgpzdGFydHhyZWYKOTMzNgolJUVPRgo=
    ------_=_NextPart_000_01C9A8A2.19479FE4--
    A10 OK FETCH fuldført.
    A11 FETCH 1 (BODY[TEXT]<40336.16384>)
    * 1 FETCH (BODY[TEXT]<40336> {0}
    20/03-09 15:18:21,445 3 Done, writing bytes to ByteArrayOutputStream. Size: 40336 bytes (..common.mail.MailUtil.dumpMessageToFile.dumpMessageToFile)
    20/03-09 15:18:21,445 3 Done, writing ByteArrayOutputStream to file. (..common.mail.MailUtil.dumpMessageToFile.dumpMessageToFile)
    A11 OK FETCH fuldført.

Maybe you are looking for

  • How do I add my friends birthdays to the pre installed "birthdays" calendar on my iPad 2

    I have added birthdays to the default calendar but there is a birthdays one and I want to put my friends birthdays on that calendar but it won't let me. When I look under calendars there is a calendar called birthdays under other but I can't use it.

  • Handling error messages in OOPs ALV

    The question below is foolish.But I am a beginner so please excuse. I have successfully displayed an OOPs ALV which displays the material, batch and plant. A custom toolbar button(delete batches) has been appended to the standard toolbar. Now when I

  • How i can give date in each input for applying the exchange rate in Query.

    Hi Gurus, We have a requirement to create some currency conversion queries. In the selection screen user should be able to give four inputs. Like given below Input 1.          a)  key figures                         b) Fiscal Year                    

  • Button dosen't work properly, need help please

         In a custom component I have 5 buttons, for each button i have the roll over, roll out and on click Interaction So if you roll your mouse pointer on a button it transitions to a state that looks the same but a picture pops out and if i roll out

  • Spacebar is triggering 3  keys at  the same  time??

    anybody know why the space bar is triggering 3 keys at once. (spacebar = and =F6 =keys) very weird. I am seeing this via the keyboard viewer. Something very weird happening. Also if I am not using my Mac, it asks to shutdown , sleep, etc. Anyway, I c