Objects in Sockets

Hi,
I'm writing a server <-> client application and I have a problem while sending Objects.
Generally, everything is fine as far as I don't want to send object back and forth. My problem by example:
- Server creates an object for instance myObject = new MyObject();
- Server puts an this object on a list myObjectList.add(myObject);
- Server sends the Object to the client via writeObject
- Client recives the package myObject = (myObject)input.readObject();
- Client sets a text in the object myObject.setText("Hello server");
- Client sends the object back to the server
- Server gets the object myObjectFromClient = (MyObject)input.readObject();
and here comes my problem out. Server will be reciving many such objects and he is going to check, which response did he get, but when I'll do a contains() check on a list of MyObjects: myObjectList.contains(myObjectFromClient); I'll get a false in result :(
Is there any way to recognize same objects when using sockets? one and obvious method is to set a field in an object with an ID and then I'll be able to recognize it when it gets back, but looks very non proffesional to me...
Thanks in advance
Maciej

By recognizing if the objects are the same I mean recognizing which object on the server side is the object that came back from the client (I've send the object earlier to the client).
Anyway, the idea you suggest seems to be my solution, I can set the ID's as fields in the object and than overload equals() method to compare ID's and everything should work fine with a minimum amount of changes. Thanks!

Similar Messages

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

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

  • 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();
    }  

  • Error by submitting objects with socket

    Hallo,
    I allways get the following error massage:
    Error:
    java.net.ConnectException: Connection timed out: connect
    Exception in thread "Thread-0" java.lang.NullPointerException
    at com.Receiver.read(Receiver.java:36)
    at Input.write(Kommunicator.java:111)
    at Input.run(Kommunicator.java:137)
    Error:
    java.net.ConnectException: Connection timed out: connect
    Here is my code:
    import com.*;
    import TerminalIO.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class Kommunicator
         public static void main(String [] args){
              KeyboardReader inread = new KeyboardReader();
              int port = inread.readInt();
              String ip =inread.readLine();
              Emitter out = new Emitter(ip, port);
              Input in= new Input(new Receiver(ip, port));
              try{
                   in.start();
                   boolean flag=true;
                   while(flag){
                        out.open();
                        if(line.equalsIgnoreCase("\\quit")){
                             out.write("User left");
                             in.interrupt();
                             flag=false;
                        else{
                             out.write(line);
                        out.close();
              catch(IOException e){
                   System.out.println("Error:\n"+e.toString());
    class Input extends Thread
         private Receiver out;
         public Input(Receiver a){out=a;}
         private void open(){
              try{
                   out.open();
                   super.start();
              catch(IOException e)
                   System.out.println("Error:\n"+e.toString());
         private void close(){
              try{
                   out.close();
              catch(IOException e)
                   System.out.println("Error:\n"+e.toString());
         private void write(){
              try{
                   Object temp=out.read();
                   if(!temp.equals(null))
                        String line=temp.toString();
                        do
                        System.out.println("Other:"+line);
                        line=out.read().toString();
                        }while(!line.equals(""));
              catch(IOException e)
                   System.out.println("Error:\n"+e.toString());
              catch(ClassNotFoundException e)
                   System.out.println("Error:\n"+e.toString());
         public void run()
              open();
              write();
              close();
    package com;
    import java.net.*;
    import java.io.*;
    public class Receiver
         private String ip;
         private int port;
         private ObjectInputStream ois;
         private Socket sock;
         public Receiver(String a, int b)
              ip=a;
              port=b;
         public void open() throws IOException
              sock = new Socket(InetAddress.getByName(ip), port);
              ois = new ObjectInputStream(sock.getInputStream());
              sock.setSoTimeout(3000);
         public void close() throws IOException
              ois.close();
              sock.close();
         public Object read() throws IOException,ClassNotFoundException
              Object temp=null;
              temp=ois.readObject();
              return temp;
         public int getPort()
         {return port;}
         public String getIp()
         {return ip;}
    package com;
    import java.io.*;
    import java.net.*;
    public class Emitter
         private String ip;
         private int port;
         private Socket sock;
         private ObjectOutputStream oos;
         public Emitter(String a, int b)
              ip=a;
              port=b;
         public String getIp()
         {return ip;}
         public int getPort()
         {return port;}
         public void open() throws IOException
              sock = new Socket(InetAddress.getByName(ip),port);
              oos =new ObjectOutputStream(sock.getOutputStream());
              sock.setSoTimeout(3000);
         public void write(Object a) throws IOException
         {oos.writeObject(a);}
         public void close() throws IOException
              oos.close();
              sock.close();
    }I hope you can help me with my problem and I hope you can answer my questions;
    1) is it a general problem with socket, that it is not allowed to submit objects on a permanent way?
    2) is it there another way how to submit object?
    3) can the problem be caused through trying to submit packeges in a lan?

    1. When you get an exception trying to construct any object, it is poor practice to print and ignore it.
    2. It is invalid to continue as though the object had been constructed.
    3. In this case you failed to connect but then continued to the read method using a null socket reference.
    4. You need to restructure your code so that it reacts correctly to exceptions.
    5. Then you need to solve the question of why the connect failed.

  • 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);
    }

  • 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();

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

  • Sending 2 objects through sockets?

    Hi there,
    I have 2 questoins here...
    The first is....
    Ive made a simple game that moves a image around a screen using the arrow keys. When i start the server it listens for connections and then I run the client. I'm able to get 2 instances of the objects running in 2 different swing frames but at the moment when I move the image around the screen it only moves in one window and not in the other. I would like the coordinates of the image in one window to be the same as the other when I move it.
    this is my server class...
      public void run() {
               try {
                  oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());i move the pacmanGame on my PacmanGamePanel(pgp) which is on a pacmanGameFrame(pgf)
    This is my Client class....
    public static void main(String argv[]) {
                PacmanGameFrame pgf = new PacmanGameFrame();
               ObjectOutputStream oos = null;
               ObjectInputStream ois = null;
               //ObjectInputStream ois2 = null;
               Socket socket = null;
               PacmanGame pacgame = null;
               Ghost ghost = null;
               int port = 4444;
               try {
                 // open a socket connection
                 socket = new Socket("localhost", port);
                 // open I/O streams for objects
                 oos = new ObjectOutputStream(socket.getOutputStream());
                 ois = new ObjectInputStream(socket.getInputStream());
                 //ois2 = new ObjectInputStream(socket.getInputStream());
                 while (true) {
                        // read an object from the server
                        pacgame = (PacmanGame) ois.readObject();
                        ghost = (Ghost) ois.readObject();
                        oos.reset();
                        I was hoping you could tell me why its not sending the object over from my client.
    The second thing is i've coded a Ghost class the exact same way as my PacmanGame class which contains how the image moves around the screen and its methods etc. For some reason its not displaying at all on either the client or the server when i try to send the object across.
    I am trying the same way as sending the pacmanGame() but it doesn't work....
    public void run() {
               try {
                  oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());I have a panel class which prints out the coordinates of the ghost
    public void paint(Graphics g) {
            super.paint(g);
            if(ingame) {
                 Graphics2D g2d = (Graphics2D)g;
                g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
            for (int i = 0; i < ghosts.size(); i++) {
                 Ghost ghost = (Ghost)ghosts.get(i);
                 if(ghost.isVisible())
                      g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
            g2d.setColor(Color.WHITE);
            else {
                 System.out.println("GAME OVER");
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }Help on either question would be great.
    1. why wont the image move on both server and client sides.
    2. How can i get my ghost class to display?
    If you need more info/code let me know..
    Thanks alot.

    Ok i called flush() on the output and commented out reset() on the input but still the same problem.
    oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());
                  oos.flush();
    pacgame = (PacmanGame) ois.readObject();
                        ghost = (Ghost) ois.readObject();I think i've figured it out now and its to do with my paint() within gamePanel..
    public class PacmanGamePanel extends JPanel implements ActionListener {
        private Timer timer;
        private PacmanGame pacmanGame;
        private Ghost ghost;
        private ArrayList ghosts;
        private boolean ingame;
        private int B_WIDTH;
        private int B_HEIGHT;
        private int[][] pos = {
                  {50, 50}
    public void paint(Graphics g) {
            super.paint(g);
            if(ingame) {
                 Graphics2D g2d = (Graphics2D)g;
                g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
            for (int i = 0; i < ghosts.size(); i++) {
                 Ghost ghost = (Ghost)ghosts.get(i);
                 if(ghost.isVisible())
                      g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
            g2d.setColor(Color.WHITE);
            else {
                 System.out.println("GAME OVER");
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }Can you help?

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

  • URL object and sockets

    I wrote an applet. It connects to a web server and reads in info. Then i got a problem. I used URL class to open a connection (url.openConnection().getInputStream()) to the web resource (http://web site:xxx/data?params). URL internally opens a socket connection to the resource. Sockets are a protected resource in applets and the applet crashed sighting the security manager. The only way to that i know to make it work, is to sign the applet.
    Is there any other way to open a stream to this web resource with out opening sockets or any other restricted resources?

    I wrote an applet. It connects to a web server and
    reads in info. Then i got a problem. I used URL class
    to open a connection
    (url.openConnection().getInputStream()) to the web
    resource (http://web site:xxx/data?params). URL
    internally opens a socket connection to the resource.
    Sockets are a protected resource in applets and the
    applet crashed sighting the security manager. The only
    way to that i know to make it work, is to sign the
    applet.
    Is there any other way to open a stream to this web
    resource with out opening sockets or any other
    restricted resources?Absolutely, you can use the URL object instead of a socket. A URL object allows you to read anything that a Web server can serve as along as you use the http protocol. Here is an example:
    URL theURL = new URL("http://www.there.com/index.html") ;
    URLConnection conn = thURL.openConnection() ;
    conn.connect() ;
    DataInputStream dis = new DataInputStream(conn.getInputStream()) ;
    FileOutputStream fos = new FileOutputStream(someOutputFile) ;
    int data = dis.read() ;
    while (data != -1)
    fos.write(data) ;
    data = dis.read() ;
    dis.close() ;
    fos.close() ;The above code needs to be enclosed in a try catch block but that is about all it takes.

  • 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 :)

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

  • Object can't be send over to the server.

    Hi to everyone,
    I'm doing a connection between client and server. The client will send image from the platform to the server. The server will then create an folder in the server-side to store the images.
    Thank you for reading. Hope to hear from you soon. Anytime you need clarifation, you could ask. I'll be more willingly to feel you in in more details.
    IMclient.java -- file
    import java.awt.geom.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    // ========================== START OF IMAGECLIENT ===========================
    public class IMclient extends JFrame implements ActionListener,ChangeListener
    private JMenuBar mainMenu;
    private JMenuItem open, save, exit, scale;
    private JMenu fileMenu, editMenu;
    private JPanel mainPane, butPane;
    private JFileChooser imagesFile;
    private JButton butSend;
    private JLabel imageLabel; //A display area for a short text string or an image, or both
    JPanel imagePanel;
    JLabel imgPanel = new JLabel();
    BufferedImage buffImage=null;
    BufferedImage bimage;
    ImageStorage dImage=null;
    // JSlider variable
    final int MIN = 0;
    final int MAX = 255;
    final int INIT = MAX/2;
    JSlider redSlider, greenSlider, blueSlider;
    // BufferedImage bimage;
    int r,g,b;
    int w,h;
    int pixels[];
    Image img;
    String fname= "babymin05.gif";
    // Declare all the Input/Output object variables.
    Socket toHost = null;
    //PrintWriter out = null;
    ObjectInputStream in = null;
    ObjectOutputStream objectOut = null;
    Container cpane;
    // ================================ Constructor ===============================
    public IMclient(String host, int port){
    initGUI();
    initSocket(host, port);
    dImage = new ImageStorage(fname);
    updateImage();
    public void updateImage()
    buffImage = dImage.getImage(); //return buffered image
    // img = (Image)bimage; //cast buffered image as images
    displayImage(buffImage); //display the images
    //added from rgbslider
    //JSlider RedSlider,BlueSlider,GreenSlider;
    public void displayImage(BufferedImage buffImage)
    //to create and display an image
    //BufferedImage bimage = rgb.getColor();
    ImageIcon icon = new ImageIcon(buffImage);
    System.out.println(icon);
    imgPanel.setIcon(icon);//to set image visible
    imgPanel.repaint();
    public void stateChanged(ChangeEvent e)
    //return buffered image from ImageStorage class.
    bimage = getColor();
    // displayImage(bimage);
    public BufferedImage getColor()
    //to get the array of pixels of the buffered image
    pixels = new int[dImage.getWidth()*dImage.getHeight()];
    //return the pixels value of bufferedImage
    pixels = dImage.getPixelsArray();
    int [] rgb = new int[3];
    int pix=0;
    for (int i=0 ; i<pixels.length ; i++)
    //to get the r,g,b value from the array
    rgb = dImage.getRGB(pixels);
    r = redSlider.getValue();
    g = greenSlider.getValue();
    b = blueSlider.getValue();
    //to set the pixels to the final value
    pixels = dImage.setRGB(r,g,b);
    dImage.setPixels(pixels);
    //to set the pixels array value and the RGB value
    dImage.setImage(pixels);
    bimage = dImage.getImage();
    //to return the buffered image
    return bimage;
    public JPanel sliderGUI()
    JPanel slidePanel = new JPanel();
    slidePanel.setLayout(new GridLayout(3,2));
    setSlider();
    JLabel redLabel = new JLabel("Red");
    JLabel blueLabel = new JLabel("Blue");
    JLabel greenLabel = new JLabel("Green");
    slidePanel.add(redLabel);
    slidePanel.add(redSlider);
    slidePanel.add(blueLabel);
    slidePanel.add(blueSlider);
    slidePanel.add(greenLabel);
    slidePanel.add(greenSlider);
    return slidePanel;
    // setSlider() consists of the three silders (r,g and b).
    private void setSlider(){
    blueSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
    blueSlider.setMajorTickSpacing(MAX);
    blueSlider.setMinorTickSpacing(MIN);
    blueSlider.setPaintLabels(true);
    redSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
    redSlider.setMajorTickSpacing(MAX);
    redSlider.setMinorTickSpacing(MIN);
    redSlider.setPaintLabels(true);
    greenSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
    greenSlider.setMajorTickSpacing(MAX);
    greenSlider.setMinorTickSpacing(MIN);
    greenSlider.setPaintLabels(true);
    blueSlider.addChangeListener(this);
    redSlider.addChangeListener(this);
    greenSlider.addChangeListener(this);
    public BufferedImage getBufferedImage()
    return bimage;
    // ================================ initGUI() =================================
    public void initGUI()
    cpane = getContentPane();
    cpane.setBackground(Color.white);
    cpane.setLayout(null);
    //to set the close menu on the menubar
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    //Open the menu in order to img from any folder
    imagesFile = new JFileChooser();
    imagesFile.addActionListener(this);
    //create an intermedia panel to hold panel and button
    mainMenu = new JMenuBar();
    setJMenuBar(mainMenu);
    setContentPane(cpane);
    fileMenu = new JMenu("File");
    mainMenu.add(fileMenu);
    editMenu = new JMenu("Features");
    mainMenu.add(editMenu);
    /* == JMenuItem(open, save, exit) to be added into the JMenu(fileMenu) == */
    open = new JMenuItem("Open...");
    save = new JMenuItem("Save...");
    exit = new JMenuItem("Exit...");
    scale = new JMenuItem("Scale");
    fileMenu.add(open);
    fileMenu.add(save);
    fileMenu.add(exit);
    editMenu.add(scale);
    /* =================== End of adding JMenuItem() ======================== */
    //add events to the JMenuItem(open, save, exit)
    open.addActionListener(this);
    save.addActionListener(this);
    exit.addActionListener(this);
    scale.addActionListener(this);
    /* =============== Create a button =======================*/
    butSend = new JButton("Send");
    butSend.addActionListener(this);
    JPanel butPane = new JPanel();
    butPane.setLayout(new BorderLayout());
    butPane.add(butSend);
    /* =============== End Create button =======================*/
    /* =============== Create a Image Panel =======================*/
    imgPanel = new JLabel();
    imagePanel= new JPanel(new BorderLayout());
    //imgPanel.setBorder(BorderFactory.createRaisedBevelBorder());
    imagePanel.setBorder(BorderFactory.createRaisedBevelBorder());
    //imageLabel = new JLabel();
    imagePanel.add(imgPanel);
    /* =============== End of Image Panel =======================*/
    // creates a new Panel
    JPanel rgb=sliderGUI();
    cpane.add(rgb);
    cpane.add(imagePanel);
    cpane.add(butPane);
    Insets insets = cpane.getInsets();
    imagePanel.setBounds(50 + insets.left, 20 + insets.top, 300, 236);
    butPane.setBounds(400 + insets.left, 220 + insets.top, 90, 40);
    rgb.setBounds(50 + insets.left, 300 + insets.top, 400, 250);
    //to set the size of the frame
    setSize(1024,768);
    //to set the main pane visible to the user
    setVisible(true);
    // =========================== actionPerformed() ==============================
    public void actionPerformed(ActionEvent e)
    if(e.getSource()==(open))
    imagesFile.showOpenDialog(this); //to have the OPEN dialog box
    if(e.getSource() == imagesFile)
    //to get the file from the exact folder that the user clicks on
    fname = imagesFile.getSelectedFile().getAbsolutePath();
    updateImage();
    if(e.getSource() == (exit))
    System.exit(0); //exit the program
    if(e.getSource() == butSend)
    sendImage(img);
    /* ========================== initSocket ================================
    * Set up the socket connection to the server.
    * 1: connect to the server at <host>, <port>.
    * 2: getOutputStream() will return an output stream for our socket (ie
    the stream is FROM the client TO the server. Since we want to send
    Image objects to the server, we need to create a stream which can
    send object, ie. an ObjectInputStream.
    3: getInputStream will return an input stream for our socket (ie. stream
    is FROM the server TO the client. We use this to create a stream that
    can transmit formatted characters.
    protected void initSocket(String host, int port)
    try{
    toHost = new Socket(host, port); //1
    //always do OUT then do IN
    objectOut = new ObjectOutputStream(toHost.getOutputStream()); //2
    in = new ObjectInputStream(toHost.getInputStream()); //3
    sendObject(bimage);//here got problem ba
    Object input = null;
    try{
    while((input = in.readObject()) != null) //test whether object is null
    Image img = (Image)input;
    sendImage(img);
    }catch (Exception e){}
    toHost.close();
    catch (UnknownHostException e)
    System.err.println("Unknown host in initSocket()");
    catch (IOException e)
    System.err.println("IO error in initSocket()");
    /* =========================== sendObject() ==============================
    * objectOut is the ObjectOutputStream. To send an object across the stream,
    * use the writeObject() method of ObjectOutputStream. The flush() method
    * ensures that data is sent.
    protected void sendObject(Object obj)
    try{
    objectOut.writeObject(obj);
    objectOut.flush();
    }catch(IOException e){
    System.out.println("Sending failed");
    System.exit(1);
    /* =========================== sendImage() ==============================
    * sendImage() creates the requested Image Object, then calls sendObject() to
    * send the image's width, height, and raw data to the server. The server uses
    * these to reconstruct the image, we could use the ImageIO class to read the
    * image file.
    * The getImage() method return immediately, even if the image data has been
    * fully loaded. Once the data is locked, the width and height, values using the
    * getWIdth() and getHeight() methods.
    protected void sendImage(Image img)
    int w,h;
    //get the image from the imagePanel and return the buffered image
    img = dImage.getImage();
    while ((w = img.getWidth(null)) == -1){}
    //System.out.println("Width of image: "+ w);
    while ((h = img.getHeight(null)) == -1){}
    int[] buffer = new int[w * h];
    /* The PixelGrabber class implements an ImageConsumer which can be
    * attached to an Image or ImageProducer object to retrieve a subset
    * of the pixels in that image.
    PixelGrabber px = new PixelGrabber (img,0,0,w,h,buffer,0,w);
    try{
    px.grabPixels();
    }catch (InterruptedException ie){
    System.err.println("Pixels grab failed");
    sendObject(new Integer(w));
    sendObject(new Integer(h));
    sendObject(buffer); //buffer contains all the bytes for the image
    public static void main(String [] args)
    if(args.length != 2)
    System.err.println("Requirement Paramenters: <host>,<port number>");
    System.exit(0);
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    IMclient is = new IMclient(host,port);
    IMserver.java-- file
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class IMserver
    Image images;
    public IMserver()
    try
    start();
    }catch (IOException ioe){
    System.err.println("Start Failed:"+ioe);
    private void start() throws IOException
    ServerSocket ss = new ServerSocket(22222);
    while(true)
    new ImageServerConnection(ss.accept(), images).start();
    public static void main(String[] args)
    IMserver im = new IMserver();
    class ImageServerConnection extends Thread
    //Declare the Input/Output object variable
    Socket clientSocket = null;
    ObjectOutputStream objectOut = null;
    ObjectInputStream inObject = null;
    Image img;
    /* ====================== ImageServerConnection ================================
    *ImageSeverConnection is a subclass of Thread. ImageServerConnection handles a
    * connection with a client. It has methods for initialzing a connection and for
    * receieving objects to clients.
    public ImageServerConnection(Socket client, Image img)
    clientSocket = client;
    this.img = img;
    /* ========================= run() ===========================
    * run() is overrriden from Thread. In this case, we call the
    * newSocket method to initialize the socket and perform initial
    * tasks.
    public void run()
    try{
    newSocket();
    }catch(IOException ioe){
    System.err.println("Socket failed: " + ioe);
    /* ========================= newSocket() ===========================
    * This is where we do all the client connection work
    private void newSocket() throws IOException
    inObject = new ObjectInputStream(clientSocket.getInputStream());
    //objectOut = new ObjectOutputStream(clientSocket.getOutputStream());
    getImage();
    clientSocket.close();
    /* =============================== getImage() =================================
    * getImage() assumes that a connection already exists to the server.
    * First, getImage transmits the image we want to get.
    * Then, we wait to read the 3 objects sent by the server's ObjectOutputStream:
    -- an Integer object, representing the width of the image
    -- an Imteger object, representing the height of the image
    -- an Image object
    * The first two are Integer objects, NOT primitive int types. This
    * is because the ObjectOutputStream can only transmit objects, not primitive
    * types (to transmit primitive types, use a DataOutputStream).
    * 1: Read the three objects sent by the server. Note each object must be cast to
    its appropriate type, since readObject() returns an Object. To get the value
    of an Integer object, we use its intValue() method, which returns the primitve
    int value of the Integer.
    * 2: The buffer object is an array of integers, which represents the image
    data. In other words, buffer is an array of integers in memory which is
    the source of the raw image data. Java has a special MemoryImageSource
    class which is used to construct Images from raw data in memory. So, in
    step 3, we create a MemoryImageSource object using the width, height, and
    buffer objects.
    * 3: We want to create an Image object using the MemoryImageSource object we
    created in step 3. To do this, we use the createImage() method of the
    Component class. Since this client class extends Frame, and Frame is a
    subclass of Component, we can call createImage() directly.
    * 4: Once the Image is created, it will be passed into the folder for storage
    private void getImage()
    Component c=null;
    try{
    objectOut.writeObject(img);
    objectOut.flush();
    int w = ((Integer)inObject.readObject()).intValue();
    int h = ((Integer)inObject.readObject()).intValue();//1
    int [] buffer = (int[])inObject.readObject(); //2
    Image img = c.createImage(new MemoryImageSource(w, h, buffer, 0, w)); //3
    //create an new folder to store those sent images
    File f = new File ("C:\\Sweet_Memory");
    //you can also check whether such folder exists or not.
    if (!f.exists ()){
    f.mkdir ();
    //how to store image into the file????
    }catch(Exception e){
    System.out.println("Server-side: "+ img);
    System.err.println("Receiving failed: "+ e);
    }

    The codes below have error message showing "IO error in initSocket() " which is in the initSocket method and "Sending failed" which is in sendObject method. HOwever i can't figure out why this error message is shown. Can anyone kindly help me out? Did i declare the wrong thing?
    Please clarify with me if i'm not clear, thank a lot. Any help will be appreaciated.
    IMclient.java
    public class IMclient extends JFrame implements ActionListener,ChangeListener
         // Declare all the Input/Output object variables.
        Socket toHost = null;
        ObjectInputStream in = null;
        ObjectOutputStream objectOut = null;
        public void actionPerformed(ActionEvent e)
          if(e.getSource() == butSend)
                sendImage(img);
        protected void initSocket(String host, int port)
            try{
         toHost = new Socket(host, port); //1
         //always do OUT then do IN
         objectOut = new ObjectOutputStream(toHost.getOutputStream()); //2
         in = new ObjectInputStream(toHost.getInputStream()); //3
         sendObject(bimage);
          Object input = null;
          try{
          while((input = in.readObject()) != null) //test whether object is null
                    Image img = (Image)input;
                   sendImage(img);
                  }catch (Exception e){}
         toHost.close();
                  catch (UnknownHostException e)
         System.err.println("Unknown host in initSocket()");
                  catch (IOException e)
         System.err.println("IO error in initSocket()");
    protected void sendObject(Object obj)
             try{
         objectOut.writeObject(obj);
         objectOut.flush();
             }catch(IOException e){
         System.out.println("Sending failed");
                         System.exit(1);
    protected void sendImage(Image img)
             int w,h;
             //get the image from the imagePanel and return the buffered image
             img = dImage.getImage();
              while ((w = img.getWidth(null)) == -1){}
              while ((h = img.getHeight(null)) == -1){}
              int[] buffer = new int[w * h];
               PixelGrabber px = new PixelGrabber (img,0,0,w,h,buffer,0,w);
               try{
                     px.grabPixels();
                }catch (InterruptedException ie){
                      System.err.println("Pixels grab failed");
                sendObject(new Integer(w));
                sendObject(new Integer(h));
                sendObject(buffer); //buffer contains all the bytes for the image
    public static void main(String [] args)
                if(args.length != 2)
                   System.err.println("Requirement Paramenters: <host>,<port number>");
                  System.exit(0);
                String host = args[0];
                int port = Integer.parseInt(args[1]);
                IMclient is = new IMclient(host,port);
    IMserver.java
    public class IMserver
         Image images;
         public IMserver()
               try
         start();
               }catch (IOException ioe){
         System.err.println("Start Failed:"+ioe);
          private void start() throws IOException
                  ServerSocket ss = new ServerSocket(22222);
                  while(true)
         new ImageServerConnection(ss.accept(), images).start();
           public static void main(String[] args)
         IMserver im = new IMserver();
    class ImageServerConnection extends Thread
             //Declare the Input/Output object variable
            Socket clientSocket = null;
            ObjectOutputStream objectOut = null;
            ObjectInputStream inObject = null;
             Image img;
             public ImageServerConnection(Socket client, Image img)
         clientSocket = client;
         this.img = img;
             public void run()
         try{
                newSocket();
         }catch(IOException ioe){
             System.err.println("Socket failed: " + ioe);
              private void newSocket() throws IOException
                     inObject = new ObjectInputStream(clientSocket.getInputStream());
                     getImage();
                      clientSocket.close();
               private void getImage()
                        Component c=null;
         try{
                  objectOut.writeObject(img);
                   objectOut.flush();
                     int w = ((Integer)inObject.readObject()).intValue();
                     int h = ((Integer)inObject.readObject()).intValue();//1
                     int [] buffer = (int[])inObject.readObject(); //2
                     Image img = c.createImage(new MemoryImageSource(w, h, buffer, 0, w)); //3
         }catch(Exception e){
                                System.err.println("Receiving failed: "+ e);
    }

Maybe you are looking for