Send Java objects through a socket

I want to send some java objects to a J2SE server from a J2me socket. In normal j2me socket there is no way of putting whole obejct to the output stream. Is there any way that you can send a object from a socket ? Please advice..
Thanks.

Check this article on making serializable objects in MIDP. If the objects you want to send receive across the network implement this, then you can easily transform them into byte arrays and back to objects so they can be sent across a network.
shmoove

Similar Messages

  • Sending Java Objects to Flex

    Hi All ,
       I have a Flex+Java Application , which is running fine , and i am sending the List of employess to Flex from my Java(Struts) like :(In flex i am using HTTPService)(Employee is a java bean)
    XStream xstream = new XStream();
    EmpDAO dao=new EmpDAO();
    ArrayList<Employee> empList=null;
    empList=(ArrayList<Employee>) dao.getEmployees();
    response.setContentType("text/xml");
    xstream.toXML(empList,response.getWriter());
    This is working fine , but now my requirement is to send java Objects to Flex.
    Is there any way to send Java objects to Flex ??
    Please help me...

    Looks like the properties in your Java class are having
    default scope. Please make sure the getters and setters for the
    properties are public and are following Java beans naming
    conventions. Can you also try creating a DataPoint class in the
    Flex application and map it to the respective Java class. One more
    thing is that, can you change the type of "data" varible in the
    Flex application to ArrayCollection.
    Hope this helps.

  • Send many files through a socket without closing Buffered Streams?

    Hi,
    I have an application that sends/receives files through a socket. To do this, on the receiver side I have a BufferedInputStream from the socket, and a BufferedOutputStream to the file on disk.
    On the sender side I have the same thing in reverse.
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)
    therefore, how can I tell the receiver that it has reached the end of a file?
    Can you show me any examples that send/receive more than one file without closing any streams/sockets?

    Hi,
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)Its not if you want to continuosly listen to the particular port.. like those of server, you need to use ServerSocket.
    for sending multiple files the sender(Socket) can request the file to server (ServerSocket). read the contents(file name) and then return the file over same connection, then close the connection.
    For next file you need to request again, put it in loop that will be better.
    A quick Google gives me this.
    Regards,
    Santosh.

  • 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 Java object using E-Mail

    Dear Experts,
    In my application I am trying write java Object in a file. Then I have to attach that file with an E-Mail. In the receiver side I have to download the file and read the Java Object from file.
    The Problem is , when I am sending and receiving mail using outlook Express, My file is reduced by some Kbs(Example , I am sending 66kb but I am receiving only 64Kb).
    If any of you have some ideas to solve the above problem, please let me know.
    With Thanks
    Panneer

    Perhaps you are trying to send binary but e-mail must be in text or the data will get filtered/mangled.

  • Is it possible to send Java Object as parameter to an applet

    Is there a way to communicate to the applet using java objects instead of String parameters.
    can we do the following while invoking an applet
    <applet code=some.class>
    <param name=name value=object/>
    </applet>
    in applet
    Object obj = (Object) getParameter("name");
    Please le me know if you have any suggestions.
    Thanks!

    in the applet:
    URL url = new URL("mypage.jsp?somearg=somevalue");
    URLConnection conn = url.openConnection();
    conn.connect();
    ObjectInputStream in = new ObjectInputStream(conn.getInputStream());and in the JSP (although servlets would be better for this):
    <%@page import="java.io.*, java.util.*"
    %><% // This is important... if you are going to use JSP, you can't allow any newlines,
    // which is why servlets are better for this type of thing...
    String somearg = request.getParameter("somearg");
    ObjectOutputStream objOut = new ObjectOutputStream(response.getOutputStream());
    objOut.writeObject(someObject);
    objOut.flush();
    objOut.close();
    %>

  • Accessing java objects through javascript

    anybody know a how to get an image from java to javascript... example you get an image from a scanner through java... and then want to use it in javascript

    anybody know a how to get an image from java to
    javascript... example you get an image from a scanner
    through java... and then want to use it in javascripthttp://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/java_js.html

  • Help: Send and Receive through Datagram Socket

    I am trying to create a client/server using Datagram Socket (UDP) as communication. I have a Recive and a Send class that implements runnable and are responsible for receiving and sending of message. I have two other classes Server and Client that are utilizing these. Now i can get the receive and send to work fine, but i am having trouble retrieving the message from the receive thread that i created in each of server/client. I've tried inserting a method so the server/client can call on to get the message (Receive.Get_Message()) but unfortunately this isn't working as i wanted. Since my server and clients are not implemented as runnables, i can only issue the command in some serialize fashion. What i really want to do is that whenever the message is receive by the Receive thread, it will immediately be send back to server/client and display right then, independent of what i was doing. (i have a command interface for S/C so it just sits there to wait for command, now what i would like is to have the S/C display the message it gets immediately after it gets it even when it's waiting for user input. since my program is waiting for a command, i really could not use the method describe above to achieve this) Could anyone help me with this?
    Thanks!
    Hung-Hsun Su

    u cant use the observer pattern. or at least i can't figure out how to implement it with sockets.
    you should use threading.
    public void run()
      while(true)
         //keep reading from socket
         InStream output = socket.getInputStream();
         InputStreamReader ir = new InputStreamReader(output)
         BufferedReader reader = new BufferedReader(ir);
         String s = null;
         while(s == null)
           s = reader.readLine();
         //then do whatever you want to the received string "s"
    }

  • Sending Custom Java Objects over XML!!

    Hello all !
    Can anybody please tell me how can I send custom Java Objects through XML? For example we can set attributes for a node using the setAttribute method, it accepts only strings, also the setTextContent method requires text and sets the node's value.Can I some way set my own Java object as the value of a particular node or attach it to the node?
    Thanks in advance.

    Kami_Pakistan wrote:
    So I should rather go for Marshalling or Serialization or is there any other work-around possible?I don't know. You didn't say what you had against text formats. Since all Java objects are composed of primitives when you get right down to the bottom, everything in Java can be serialized as text versions of those primitives. So you're going to have to explain why you think a work-around is necessary at all.

  • Problems sending bufferedimages through a socket

    Hi everyone,
    I've got a server program that takes a screen capture as a bufferedimage, and sends it through a socket to be saved by the client program. The programs work fine, however, whenever I'm transferring the image with the code at the bottom of this post, I notice that the collision LED on my network hub flashes and I can't figure out why (Obviously there's a collision, but I don't know what causes it or how to stop it from happening). I've googled a bit for collisions and bufferedimages, but have come up with El Zilcho. I've also gone through the IO tutorial and the Socket and BufferedImage API's, but havent learned anything to solve my problem.
    Also, As it is now, if I want multiple images, I need to disconnect and reconnect repeatedly. I tried sending multiple bufferedimages throught the socket, but get the following exception:
    java.lang.illegalargumentexception:  im == null!Does anyone know of a way where I can send multiple bufferedimages through the socket without reconnecting every single time? Thanks
    Server code:
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    Rectangle screenRect = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect));
    ImageIO.write(image, "jpeg", fromClient.getOutputStream());
    fromclient.shutdownOutput();
    fromclient.close();Client code:
    BufferedImage receivedImage = ImageIO.read(toServer.getInputStream)
    toServer.close();Any help would be greatly appreciated. TIA
    Jay

    Have you tried.
    ImageIO.write(image1, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image2, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image3, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image4, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image5, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image6, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image7, "jpeg", fromClient.getOutputStream());

  • How to catch a jpeg picture sent through a socket?

    A jpeg picture is beaming back to my java code through
    a socket connection, how can I get the picture? What
    code shall I use. Thank you.

    Thank you for the response. I tried, and my code below did now
    work. It seems that the read() did not read the next byte. ANy
    ideas?
    FileInputStream fin = new FileInputStream("test2.jpg");
    do {
    imageData[i] = (byte)fin.read();
    i++;
    if (i%2000 == 0) {
    loadStatus.setText(""+i+" "+imageData);
    }while(imageData[i]>=0 && i<19998);
    fin.close();
    imageData[i] = -1;
    //create the image
    image = Toolkit.getDefaultToolkit().createImage(imageData);

  • 32-bit JVM receiving Java objects from 64-bit JVM

    Hi folks,
    Question is: will there be problems for 32-bit JVM receiving Java objects from 64-bit JVM? and vice versa.
    Our application client is running on 32-bit JVM, our server is running on 64-bit JVM. Client will send Java objects to server, and vice versa.
    My past experience suggested when sending Java objects between client and server, both client and server needs to be compiled under the same JVM version. Any advice?
    Christy

    My past experience suggested when sending Java
    objects between client and server, both client and
    server needs to be compiled under the same JVM
    version. Any advice?This is only a case if you omit explicit serialVersionUID. My advice is to ALWAYS specify it for classes you want to serialize over the wire or put into persistent storage. It is way too tricky to rely on default one to fail half a year later when some new programmer adds one new public method to a class.
    Unless you need to deserialize already existing resources, there is no need to put any magic number in serialVersionUID - just put 1 for every class you create and possibly increase it by 1 every time you want to make incompatible version (which is not happening so often, as in real world you often try to stay as compatible as possible)

  • 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 to send data to bam data object through java code

    how to send data to bam data object through java code

    I've made a suggestion in other thread: https://forums.oracle.com/thread/2560276
    You can invoke BAM Webservices (Using Oracle BAM Web Services) or use JMS integration using Enterprise Message Sources (http://docs.oracle.com/cd/E17904_01/integration.1111/e10224/bam_ent_msg_sources.htm)
    Regards
    Luis Fernando Heckler

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

Maybe you are looking for