Sending objects over sockets - issues i am having

Hi, this is my first time posting on these forums and I have exhausted my mental capacity on this problem i have been having the past few days. Hopefully somone could help me out.
I am doing a uni project, and the goal i am currently trying to achieve is to send an object (serialized) from a client to a server. I will atach the code i have written and i will explain more from there.
This is the server (part of the class, which calls this method)
Constructor:
  public Broker(String bID) throws Exception {
    brokerID = bID;
    bServer = new ServerSocket(Integer.parseInt(bID));
    System.out.println("Broker listening on port " + bID);
    this.start();
Main method
  public static void main(String[] args) throws Exception {
    new Broker("8008");
run method
  public void run() {
    while(true) {
      try {
        Socket bSocket = bServer.accept();
        System.out.println("Accepted a connection from: " + bSocket.getInetAddress());
        brokerServer(bSocket);
        bSocket.close();
        System.out.println("Connection closed");
      catch (Exception e) { e.printStackTrace(); }
Broker Server
  public void brokerServer(Socket bSocket) {
    BufferedReader in = null;
    ObjectOutputStream oos = null;
    PrintWriter out = null;
    ObjectInputStream ois = null;
    try {
      while (true) {
        oos = new ObjectOutputStream(new DataOutputStream(bSocket.getOutputStream()));
        out = new PrintWriter(new OutputStreamWriter(bSocket.getOutputStream()));
        ois = new ObjectInputStream(bSocket.getInputStream());
        in = new BufferedReader(new InputStreamReader(bSocket.getInputStream()));
        out.println("Connection with Broker on port " + brokerID + " established");
        out.flush();
        //read in first line
        String str = in.readLine();
        //if lineis null, break while loop
        if (str == null)  break;
        else {
          //a request is recieved from user to get user certificate
          if (str.trim().equals("GETUSERCERT")) {
            //read in the userName, size of paywords and user publick key (used in certificate)
            String userName = in.readLine();
            String size = in.readLine();
            PublicKey userPk = (PublicKey) ois.readObject();
            //generate user certificate
            UserCertificate uc = generateUserCertificate(userName, userPk, Integer.parseInt(size, 10));
            //send text to user stating next message is user certififcate
            out.println("SENDUSERCERT");
            out.flush();
            //user Certificate
            oos.writeObject( (UserCertificate) uc);
            oos.flush();
            break;
          if (str.trim().equals("FINISH"))
            break;
        ois.close();
        oos.close();
        out.close();
        in.close();
    catch(Exception e) { e.printStackTrace(); }
This is the client
  private void requestUserCertificate(int sizeOfPaywordChain, String BrokerID) {
    String host = "localhost";
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    PrintWriter out = null;
    BufferedReader in = null;
    Socket u2bSocket = null;
    try {
      u2bSocket = new Socket(host, Integer.parseInt(BrokerID));
      System.out.println("Connecting to Broker on port " + BrokerID);
      ois = new ObjectInputStream(new DataInputStream(u2bSocket.getInputStream()));
      oos = new ObjectOutputStream(u2bSocket.getOutputStream());
      out = new PrintWriter(new OutputStreamWriter(u2bSocket.getOutputStream()));
      in = new BufferedReader(new InputStreamReader(u2bSocket.getInputStream()));
      //Informs broker that a user certificate is being requested
      out.println("GETUSERCERT");
      //send to broker, username and size of payword chain
      out.println(userName);
      out.println(sizeOfPaywordChain);
      out.flush();
      //send user's public key accross
      oos.writeObject((PublicKey) userPublicKey);
      oos.flush();
      out.println("FINISH");
      out.flush();
      //wait for response
      while(true) {
        //read in line
        String str = in.readLine();
        //if line is null, break while loop
        if (str == null) break;
        //if line read is "SENDUSERCERT" then next line is userCertificate sent from Broker
        if (str.trim().equals("SENDUSERCERT")) {
          //read User Certificate
          userCert = (UserCertificate)ois.readObject();
          break;
        else System.out.println(str);
      //close connections and streams
      u2bSocket.close();
      ois.close();
      oos.close();
      out.close();
      in.close();
    catch (Exception e) { e.printStackTrace(); }
  }I will be regurarly checking this thread, so any other code which you think i should post i will, i can post is ASAP.
The problem
First time i run the programs, it works perfectly, however when i run the client program again, it shows this error
java.io.EOFException
     at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2438)
     at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1245)
     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
     at User.requestUserCertificate(User.java:75)
     at User.main(User.java:278)the broker server doesn't display anything.
Would anyone have any idea whats going on??
Sometimes when i run it, it might display the above error, or it might work. its about 50/50. I have read heaps of similar problems people have had and posted on this forum, but i still don't have any luck in solving this delema.
Any kind of help will be greatly appreciated.
Rish

I see one problem with the code. You are opening both ObjectInputStream ois and a BufferedReader in on the same socket. This won't work as "in" will read ahead to fill up its buffer. This could cause "ois" to find the socket already at end of stream prematurely. I would only use the Object Streams and send the strings as objects.

Similar Messages

  • Sending object over socket - please help (urgent)

    I have written a server/client application where server sends object to client.
    But on the client I've received the first message "@Line 1: Get ready!!!" TWICE but NEVER the second message "@Line 2: Please input Start".
    Please help me! Its urgent! I appreciate my much in advance.
    The source for Server:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import sendNode;
    public class TestSer {
         static sendNode sendNodeObj = new sendNode();
    static String inputLine;
         public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try {
    serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
    System.err.println("Could not listen on port: 4444.");
    System.exit(1);
    Socket clientSocket = null;
    try {
    clientSocket = serverSocket.accept();
    } catch (IOException e) {
    System.err.println("Accept failed.");
    System.exit(1);
    OutputStream o = clientSocket.getOutputStream();
    ObjectOutput out=new ObjectOutputStream(o);
    BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        clientSocket.getInputStream()));
    sendNodeObj.sendMsg="@Line 1: Get ready!!!";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    sendNodeObj.sendMsg="@Line 2: Please input Start";
    sendNodeObj.typeNode=-2;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    while (!inputLine.equalsIgnoreCase("Start")) {
         sendNodeObj.sendMsg="@Error, Please input Start";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();
    The source code for Client :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.applet.Applet;
    import sendNode;
    public class TestCli extends Applet {
    static sendNode recNodeObj=null;
    public static void main(String[] args) throws IOException {
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    Socket kkSocket = null;
    PrintWriter out = null;
    try {
    kkSocket = new Socket("127.0.0.1", 4444);
    out = new PrintWriter(kkSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    System.err.println("Don't know about host.");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to: taranis.");
    System.exit(1);
    InputStream i= kkSocket.getInputStream();
    ObjectInput in= new ObjectInputStream(i);
    try {
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
    if (recNodeObj.sendMsg.equalsIgnoreCase("@Line 2: Please input Start")) {
    out.println("Start");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    System.out.println("receive error.");
    System.exit(1);
    out.close();
    in.close();
    stdIn.close();
    kkSocket.close();
    The object to be sent:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class sendNode implements Serializable {
    String sendMsg;
    int typeNode; // -1 no ObjectNode;
    // 1 right node, 2 base node, 3 left node;
    Object objectNode;

    You forgot to reset the OOS. ObjetOutputStream keeps a buffer of objects, so if you write the same object again with changes on it, you must reset the buffer.
    out.writeObject(sendNodeObj);
    out.flush();
    out.reset();

  • URGENT : Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?. Should i use RMI or Externalize?. Any help would be appreciated.

    {snip}
    Like this:
    public class SerializableLibraryClass extends
    LibraryClass implements Serializable {
    }Then you've got a class that is exactly the same as
    LibraryClass, but is now serializable.Not quite. The base class still isn't Serializable. Take, for example, the following code:
    public class A
        public int a1;
    public class B extends A implements Serializable
        public int b1;
    B beforeSend = new B();
    beforeSend.a1 = 1;
    beforeSend.b1 = 2;
    objectOutputStream.writeObject(b);
    B afterSend = (B)(objectInputStream.readObject());Both beforeSend and afterSend have fields a1 and b1. For beforeSend, a1 = 1 and b1 = 2. For afterSend, b1 = 2 but a1 = 0. The superclass wasn't Serializable; therefore, its members weren't Serialized and, when the object was created on the other side of the stream, a1 was left at its initial value.
    In short, you can't just Serialize the subclass. That Serialization won't apply to its superclasses.

  • Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?.

    Have you considered leaving it in situ and using RMI to manipulate it remotely ?
    To be a little pedantic, if you need the "same exact object" then there's no technique that will work for you, since you can only copy an object between JVMs, not move it.
    D.

  • Problem with Sending files over Sockets

    Hi. I have a problem when I try to send files over sockets. When I send text files it works well but when I try to send .jpg or other kind of files it doesn't work well because some characters are wrong, I hope you can help me.
    Here is my code:
    //Sender code
    import java.io.*;
    import java.net.*;
    class Servidor{
         Servidor(){
              try{
                   String arch="art.jpg";
                   ServerSocket serv=new ServerSocket(125);
                   Socket socket=serv.accept();
                   System.out.println("Conectado");
                   int c;
                   BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   FileInputStream fis=new FileInputStream(arch);
                   File f=new File(arch);
                   bw.write(""+f.length());
                   bw.newLine();
                   bw.flush();
                   System.out.println("Escribiendo");
                   while((c=fis.read())!=-1){
                        bw.write(c);
                   bw.flush();
                   fis.close();
                   System.out.println("Terminado");
                   while(true){
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Servidor();
    //Client code
    import java.io.*;
    import java.net.*;
    class Cliente{
         Cliente(){
              try{
                   Socket socket=new Socket("localhost",125);
                   System.out.println("Conectado");
                   BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   long tam=Long.parseLong(br.readLine());
                   long act=0;
                   FileOutputStream fos=new FileOutputStream("resp.jpg");
                   System.out.println("Recibiendo: "+tam);
                   while(act<tam){
                        fos.write(br.read());
                        act++;
                   System.out.println("Terminado: "+act+" / "+tam);
                   fos.close();
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Cliente();
    }

    I don't think you want BufferedReader and OutputStreamWriter, you want ByteArrayOutputStream and ByteArrayInputStream . The problem is that you are sending jpegs (binary data) as text.

  • Send XML over Sockets

    I am beginning and I need to send XML formatted data from Swing Client to Server for parsing/processing/and response.
    There are no web server available to use. I think its best to use socket connection, but how do I send xml data over socket, and how do I receive it from server and parse it?
    I have read and cannot find a similar example.

    Xerces has DOMSerializer which can be used to serialize a Document object to a string. Once it's a string it's trivial to transmit over a socket connection. On the other side, to parse it, you'll have to create a StringReader for the received string and then an InputSource from the StringReader. You'll then be able to pass the InputSource to the DocumentBuilder.parse( ) method to generate a Document on the receiving side.
    Hope that helps,
    - Jesse

  • Sending objects with sockets (and making a mess thereof)

    I'm playing about with client/server interaction and have made a simple program where a server waits for a connection on its given port, accepts a socket connection and every second checks for any input from the client and sends a Point object with co-ordinates to the client
    The client in renders the Point object and every second checks for an updated Point from the server, whenever the left or right arrow keys are used the server is sent the keyevent object to process and change the co-ordinates of the point which will then be sent back
    But it doesn't work, the server thread hangs on the if statement testing for a new object to read. If the code looking for a new object is comented out, the system works perfectly (with the random co-ordinates shown, the Point object itself is held in another class and would be used if the server could read the input)
              try
                   ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                       ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                       boolean temp = true;
                       while (temp == true)
                        sleep(1000);
                        Object o = in.readObject();
                        if (in.readObject() != null)
                             parent.process.updatePoint((KeyEvent)in.readObject());
                        out.writeObject(new Point((int)(Math.random() * 200), (int)(Math.random() * 200)));
              } Could anyone advise me why it specifically doesn't work? Having said that I realise my design is probably rather inefficient and generally poor and any general tips are welcome to
    Any help appreciated

    I think we are going to need to see the other side of your program. If your code hangs at the if statement:
                        if (in.readObject() != null)
                             parent.process.updatePoint((KeyEvent)in.readObject());
                        }Then i would have to assume the object is never recieved.

  • Compressed objects over socket

    The simplest example on a tutorial http://java.sun.com/developer/technicalArticles/Programming/compression/ does work:
    // write to client
    GZIPOutputStream gzipout = new
      GZIPOutputStream(socket.getOutputStream());
    ObjectOutputStream oos = new
      ObjectOutputStream(gzipout);
    oos.writeObject(obj);
    gzipout.finish();However, what shoul be the correct way for sending/receiving multiple objects in a socket write/read loop?
    Here's an SSCCE that fails with every conceivable tweak, conceived by my weak brain.
    /* server */
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    public class LoopServer{
      public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(9999);
        Socket cs = ss.accept();
        System.out.println("client accepted");
        GZIPOutputStream gos =  new GZIPOutputStream(cs.getOutputStream());
        ObjectOutputStream oos = new ObjectOutputStream(gos);
        ObjectInputStream ois
          = new ObjectInputStream(new GZIPInputStream(cs.getInputStream()));
        int count = 0;
    System.out.println("begin loop"); // never comes here
        while (++count < 30){
          oos.writeObject(new Date());
          gos.finish();
          oos.flush();
          System.out.println((Date)(ois.readObject()));
        cs.close();
    /* client */
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    public class LoopClient{
      public static void main(String[] args) throws Exception{
        Socket cs = new Socket("localhost", 9999);
        GZIPOutputStream gos =  new GZIPOutputStream(cs.getOutputStream());
        ObjectOutputStream oos = new ObjectOutputStream(gos);
        ObjectInputStream ois
          = new ObjectInputStream(new GZIPInputStream(cs.getInputStream()));
          System.out.println((Date)(ois.readObject()));
        int count = 0;
    System.out.println("begin loop"); // never comes here
        while (++count < 30){
          System.out.println((Date)(ois.readObject()));
          oos.writeObject(new Date());
          gos.finish();
          oos.flush();
        cs.close();
    }

    ejp wrote:
    Isn't there a way to prevent that? Not unless you write a subclass of OOS which breaks the rules for writing finalizers, which you don't want to do either ...OK. I think I have come up with a sound hack that can avert the finalizer risk of socket closing.
    According to another thread:
    http://forum.java.sun.com/thread.jspa?threadID=5274508
    Ejp's recommended method did work for receiving a single byte array while my method which uses ByteArrayOutputStream and its toByteArray() didn't.
    Question: When the sender has sent a single byte array at a burst, should the receiver not use fragmentary read() or read(byte[smallsize])?. Should the receiver only use read(byte[fullsize])? If the answer is yes, then it would explain the cause of the above 'didn't work' failure.
    /* server */
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    public class LoopServer5{
      public static void main(String[] args) throws Exception{
        OutputStream os;
        InputStream is;
        ByteArrayOutputStream baos;
        ByteArrayInputStream bais;
        GZIPOutputStream gos;
        ObjectOutputStream oos;
        ObjectInputStream ois;
        DataOutputStream dos;
        DataInputStream dis;
        ServerSocket ss = new ServerSocket(9999);
        Socket cs = ss.accept();
        System.out.println("client accepted");
        os = cs.getOutputStream();
        is = cs.getInputStream();
        dos = new DataOutputStream(os);
        dis = new DataInputStream(is);
        int count = 0;
        int d;
        while (++count <= 10){
          /* in order to avert using multiple disposable OOS
           * wrapping a GOS wrapping the Socket OS in turn,
           * the Socket OS simply send a byte array as a DOS
           * thereby averting the risk of Socket OS finalization
          baos = new ByteArrayOutputStream();
          gos = new GZIPOutputStream(baos);
          oos = new ObjectOutputStream(gos);
          oos.writeObject(new Date());
          gos.finish();
          oos.close();
          byte[] ba = baos.toByteArray();
          dos.writeInt(ba.length); // ejp's recommended way of doing things  marked #
          dos.write(ba);                // #
          dos.flush();                    // #
          int size = dis.readInt();  // #
          byte[] buf = new byte[size]; // #
          dis.readFully(buf); // # simply read a byte array, not an Object
          bais = new ByteArrayInputStream(buf);
          // create an OIS from the byte array received
          // what a clever hack! ...self-praise!
          ois = new ObjectInputStream(new GZIPInputStream(bais));
          System.out.println
            ("from client: " + (Date)(ois.readObject()) + " " + count);
        cs.close();
    /* client */
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    public class LoopClient5{
      public static void main(String[] args) throws Exception{
        OutputStream os;
        InputStream is;
        ByteArrayOutputStream baos;
        ByteArrayInputStream bais;
        GZIPOutputStream gos;
        ObjectOutputStream oos;
        ObjectInputStream ois;
        DataOutputStream dos;
        DataInputStream dis;
        Socket cs = new Socket("localhost", 9999);
        os = cs.getOutputStream();
        is = cs.getInputStream();
        dos = new DataOutputStream(os);
        dis = new DataInputStream(is);
        int count = 0;
        int d;
        while (++count <= 10){
          int size = dis.readInt();
          byte[] buf = new byte[size];
          dis.readFully(buf);
          bais = new ByteArrayInputStream(buf);
          ois = new ObjectInputStream(new GZIPInputStream(bais));
          System.out.println
            ("from server: " + (Date)(ois.readObject()) + " " + count);
          baos = new ByteArrayOutputStream();
          gos = new GZIPOutputStream(baos);
          oos = new ObjectOutputStream(gos);
          oos.writeObject(new Date());
          gos.finish();
          oos.close();
          byte[] ba = baos.toByteArray();
          dos.writeInt(ba.length);
          dos.write(ba);
          dos.flush();
        cs.close();
    }  

  • Send Object with socket

    hi,
    I have defined objects which correspond to my messages, those object have only "byte" attributes and are realizable, exemple
         private byte[]      source;
         private byte[]      destination=new byte[2];
         private byte[]      n_emetteur=new byte[2];
         private byte[]      n_message=new byte[2]; ...................
    my problem is when i send and object by in.writeObject(myObject) i can't read it in the other hand, because my client is written with C language and i recieve only the name of my class package.package.myclass.
    can you help my find out best way to send my objects and be compatible with any client?
    thank's

    tmazight wrote:
    i post this after a large search on google, and how can google get its content if peaple can't post on forums!!!!That's your biggest problem right there: you seem to have the strange idea that the answer must come from a forum; even Google must find the answer there, like there is nothing else but a forum to find answers in. But no, it doesn't work that way. Where did those people you expect to spit out the solution get their knowledge from huh?
    1) books
    2) articles
    3) courses (for example by going to school)
    4) experimentation
    5) thought
    I'm pretty sure that in stead of having this need to get an answer from a forum you would in fact sit down and think about it, you will manage to solve it yourself. If you can't then I'm afraid that even your basic knowledge if Java is severely lacking and you simply need to brush up on Java using a good book.
    Start by following the hint EJP already gave you. Apparently you have some client which expects data in a very specific way which is throwing up all these boundaries that you can't seem to be able to break. HOW is that client expecting it to be? And I'm talking about specifics. Its all bytes, in what way does the client expect the bytes to be. Given that starting point, how would you be able to take what you know about Java (which will really boil down to working with primitives in stead of objects) get you to provide the information in such a way that it is how the client can work with it?
    If you require further assistance you'll have to minimally give an example of the specifications - how does the client expect the bytes. Perhaps then someone can provide you with an example of how to produce something like that using Java code.
    See how that works? You do something, someone else can do something back for you. That's the only way it is going to work.

  • Send Object through Socket

    Hi,
    I am trying to send an object from Server to Client but the ObjectInputStream.readObject() on the client blocks.
    net beans Project can be found Here .
    Why it doesn't work?
    Thanks,
    Itay

    The Server works fine... it waits for a second client after the first one get connected
    I will post here the code.
    Server Code
    public class MemoryServer
        private final static int DEFAULT_BOARD_SIZE = 4;
        private ServerSocket socket;
         * Starting the server
         * @param n integer to determine the size of the board (must be even) the board will be n*n.
         * @param port the port on which the server will listen for incoming requests
        public void startServer(int n, int port)
            try
                socket = new ServerSocket(port);
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
            while(true)
                System.out.println("Listening on port " + port);
                Socket firstPlayerSocket = null, secondPlayerSocket = null;
                try
                    firstPlayerSocket = socket.accept();
                    System.out.println("First Player Socket Open: " + firstPlayerSocket.getInetAddress() + ":" + firstPlayerSocket.getPort());
                    MemoryGame game = new MemoryGame(n, firstPlayerSocket);
                    secondPlayerSocket = socket.accept();
                    System.out.println("Second Player Socket Open: " + secondPlayerSocket.getInetAddress() + ":" + secondPlayerSocket.getPort());
                    game.setSecondPlayer(secondPlayerSocket);
                    game.start();
                catch (IOException e1)
                    try
                        e1.printStackTrace();
                        if (firstPlayerSocket != null)
                            firstPlayerSocket.close();
                        if (secondPlayerSocket != null)
                            secondPlayerSocket.close();
                    catch (IOException e2)
                        e2.printStackTrace();
    public class MemoryGame extends Thread
        private Socket firstPlayerSocket, secondPlayerSocket;
        private ObjectOutputStream firstPlayerOut, secondPlayerOut;
        private ObjectInputStream firstPlayerIn, secondPlayerIn;
        private int boardSize;
        public MemoryGame(int boardSize, Socket firstPlayer) throws IOException
            this.boardSize = boardSize;
            firstPlayerSocket = firstPlayer;
            firstPlayerOut = new ObjectOutputStream(firstPlayerSocket.getOutputStream());
            firstPlayerOut.flush();
            firstPlayerIn = new ObjectInputStream(firstPlayerSocket.getInputStream());
            TextMessage message = new TextMessage("Waiting for opponent.");  //TextMesaage extends Message which implements Serializable
            firstPlayerOut.writeObject(message);
            firstPlayerOut.flush();
        public void setSecondPlayer(Socket secondPlayer) throws IOException
            try
                secondPlayerSocket = secondPlayer;
                secondPlayerOut = new ObjectOutputStream(secondPlayerSocket.getOutputStream());
                secondPlayerOut.flush();
                secondPlayerIn = new ObjectInputStream(secondPlayerSocket.getInputStream());
                TextMessage message = new TextMessage(Constants.GAME_START_MESSAGE);
                firstPlayerOut.writeObject(message);
                firstPlayerOut.writeObject(message);
            catch(IOException e)
                firstPlayerIn.close();
                firstPlayerOut.close();
                if (secondPlayerIn != null)
                    secondPlayerIn.close();
                if (secondPlayerOut != null)
                    secondPlayerOut.close();
                throw e;
        @Override
        public void start()
            endGame();
        private void endGame()
            try
                firstPlayerIn.close();
                firstPlayerOut.close();
                firstPlayerSocket.close();
                secondPlayerIn.close();
                secondPlayerOut.close();
                secondPlayerSocket.close();
            catch (IOException e)
                e.printStackTrace();
    }Client Code
    public class MemoryClient
        private Socket socket;
        public MemoryClient(String host, int port)
            try
                socket = new Socket(host, port);
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                System.out.println("Connected to " + host + ":" + port);
                while (true)
                    try
                        Message msg = (Message)in.readObject();
                        System.out.println("Recieved");
                        if (msg instanceof TextMessage)
                            TextMessage textMsg = (TextMessage)msg;
                            if (!textMsg.getText().equals(Constants.GAME_START_MESSAGE))
                                System.out.println(textMsg.getText());
                                break;
                            MemoryFrame gameFrame = new MemoryFrame(socket);
                            gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    catch(Exception e)
                        e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
    }

  • Help need for sending object over TCP Connection

    I have
    ResultSet rs = (ResultSet)connection.getObject(1)
    and i have user's connection connected on a port
    Currently i am reading while rs.next elements , preparing somestring and i am using socket_connection.send('to_myuser',somestring) to send message
    and user receive it like (while input_stream.readLine() != null )
    etc .etc.. i am just writing some algorithm which very common.
    i want to reduce this recursion on the my server end and once user receive it , and to get all result set retrieved from that end.
    my question is , is it possible to send
    connection.send('myuser',rs);
    and how to read on the other end.
    Thanks in advance

    Just want to clarify how we can cache it..? I belive
    we have to put data somewher in the ArrayList or
    something ....which one major taskOf course caching requires that you store it in something.
    >
    second, you need a very good algorighm to query all
    your collections ... i think oracle SQL mechanism is
    very nice.... however in your recommended approach i
    have to write lots of searching and sorting
    alrogrthm... .correct?Generally no. Requests are usually limited to very few parameters and often limited only to one or zero. Thus a user first gets a list of customer names (no parameters for query) and then request the detail about a specific customer (using the customer id which is only one parameter.)
    Note that you mentioned large amounts of data. You didn't specify what large meant. However large requests should never be allowed from users (people). They can't use it anyways. Automated processes should be architected to provide for a technological solution with is cost effective.

  • Need to send object instances over the network

    I found no other way to implement a switch case to cast objects on both sides to solve my problem.
    Basically I need to send objects over a network protocol based on XML, the object is sent inside XML
    converted in base64, overall encoding of XML is utf-8.
    Let's suppose in my network there are 2 peers connected via socket.
    I have multiple instances of different types on both peers but I want to keep these instances
    synchronized. If something changes on side A, side B must receive that instance and replace
    it in the correct place (just one way, from A to B).
    When I receive such instance on B I want to cast it to it's proper instance
    of it's proper type and I am scratching my head on how could I implement this without some
    sort of unique ID table and switch case.
    If I had 1 instance per type could it be done easily?
    But I need to keep in synch many instances per type.
    Is there any dynamic casting that I can trigger based on some type/instanceID information
    I could send along the object?

    I found no other way to implement a switch case to cast objects on both sides to solve my problem.
    Basically I need to send objects over a network protocol based on XML, the object is sent inside XML
    converted in base64, overall encoding of XML is utf-8.
    Let's suppose in my network there are 2 peers connected via socket.
    I have multiple instances of different types on both peers but I want to keep these instances
    synchronized. If something changes on side A, side B must receive that instance and replace
    it in the correct place (just one way, from A to B).
    When I receive such instance on B I want to cast it to it's proper instance
    of it's proper type and I am scratching my head on how could I implement this without some
    sort of unique ID table and switch case.
    If I had 1 instance per type could it be done easily?
    But I need to keep in synch many instances per type.
    Is there any dynamic casting that I can trigger based on some type/instanceID information
    I could send along the object?

  • Sending data over and socket

    when i send messages over socket and receive it using [line = in.readLine()/code]
    if there is a \r\n it stops and makes u have to use readLine again to get the rest of the message
    is there a way to send the message so it totally ignores the \r\n and i can just use readLine once to receive my complete string in one go
    as this newline thing is very annoying
    thanks :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I assume in is of type BufferedReader? If so, that is the definition of readLine.
    Other options:
    You can use java.util.Scanner to scan until the next delimiter, which you can set.
    You can use readUTF/writeUTF defined in interfaces DataInput/DataOut by
    using classes DataInputStream/DataOutputStream or ObjectInpuitStream/ObjectOutputStream.
    If you are using object stream, you could define any serializable objects you
    like for transmission.

  • 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 &#305;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.

  • How do I write objects over a SocketChannel?

    Using the regular Socket class we can pass objects over sockets like this.
    Socket s = new Socket("127.0.0.1", 80);
    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
    out.writeObject(new Object());
    Now, I've looked through the documentation on the new Channel classes and have only seen ways to pass bytes over the channel, not an entire object. Is there an easy way to pass an entire object over a channel? Am I just missing an appropriate wrapper that adds this functionality?
    Thanks,
    Dave

    This code will help you converting an Object to a byte[]:
    //Object to send MUST implement Serializable
    SerializedObject anObject = new SerializedObject();
    //byte[] needed to send
    byte[] aByteArray = null;
    //the conversion
    java.io.ByteArrayOutputStream aByteArrayOutputStream = new java.io.ByteArrayOutputStream();
    java.io.ObjectOutputStream aObjectOutputStream = new java.io.ObjectOutputStream(aByteArrayOutputStream);
    aObjectOutputStream.writeObject(anObject);
    aObjectOutputStream.close();
    aByteArray = aByteArrayOutputStream.toByteArray();
    //When you receive the Object you should reverse the conversion
    //byte[] reveived from InputStream
    byte[] aReceivedByteArray;
    //Expected Object
    SerializedObject theExpectedObject = null;
    //the conversion
    java.io.ByteArrayInputStream aByteArrayInputStream = new java.io.ByteArrayInputStream(aReceivedByteArray);
    java.io.ObjectInputStream aObjectInputStream = new java.io.ObjectInputStream(aByteArrayInputStream);
    theExpectedObject = aObjectInputStream.readObject();
    That's one way to do it.
    You should watch out with Serializable object when sending it to another OS or JRE-version.

Maybe you are looking for