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

Similar Messages

  • Cannot send and read objects through sockets

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

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

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

  • Send files through Sockets

    how do i send an entire file through a socket...?
    thank you....

    [http://forums.sun.com/thread.jspa?forumID=11&threadID=390636] this may help you

  • Problems send string through Socket

    I'm writing a simple chat.
    The server-side, when receive a request from a client act in this way:
    1_ Choose a random port between 8000 and 8100
    2_ Verify if the port is alredy used (otherwise it randomize another port)
    3_ Create a dynamicServer instance that listen at the new randomized port
    4_ Communicate the port to the Client
    The program doesn't have any problem with the point 1, 2 and 3.
    But for some reason I can't explain, it doesn't communicate with the client.
    Can you explain me why? (I can't work it out by myself T_T)
    This is the code of the server-side:
    public class ProcessoServer extends Thread {
        private int cport, i = 0;
        public ServerSocket server;
        private Component SezionePrincipale;
        private PrintStream cPort;
        private int[] portUsed = new int[100];
        private ChPort choose;
        @Override
        public void run()
            try {
            while(true) {
                    server = new ServerSocket(7777);
                    Socket s1 = server.accept();
                    if(s1.getInetAddress().toString().equals("/127.0.0.1"))
                        server.close();
                        s1.close();
                        break;
                    else {
                        cport = 8000 + (int)(Math.random() * 100);
                        choose = new Chport(cport, portUsed);
                        while(choose.Check() == false)
                            cport = 8000 + (int)(Math.random() * 100);
                            choose = new Chport(cport, portUsed);
                        portUsed[i] = cport;
                        i++;
                        new DynamicServer(cport);
                        cPort = new PrintStream(s1.getOutputStream());
                        cPort.println(cport);
                        cPort.flush();
                        cPort.close();
                        s1.close();
            catch(IOException ex)
            //an error
        public void removePort(int port)
            for(int b = 0; b <= portUsed.length; b++) {
                if(port == portUsed) {
    portUsed[b] = -1;
    public void haltServer() throws UnknownHostException, IOException {
    Socket stop = new Socket("127.0.0.1", 7777);
    This is the code of the client-side.public Connection(InetAddress ip) throws IOException
    Socket s1 = new Socket(ip, 7777);
    BufferedReader port = new BufferedReader(new InputStreamReader(s1.getInputStream()));
    Integer newPort=Integer.parseInt(port.readLine());
    System.out.println("the new port is "+String.valueOf(portaNuova));
    s2 = new Socket(ip, newPort);
    port.close();
    s1.close();

    M3kka wrote:
    I'm doing this because I thought that every single conversation (I'm not exactly writing a chat, the program should be something more similar to an Instant Messager) needs a single SocketIt does not require new Server Sockets. Each Socket is unique while sharing the same server port.
    Am I wrong? Yep.
    As I indicated, this is a pretty common misconception. The uniqueness of each socket is made using several pieces of information, the host and port on one end and the host and port on the other end. One of these pieces of information must be unique. How this is handled is that the client is generally speaking assigned a random port by the client TCP implementation (aka the OS).
    At any rate you don't have to go through these gyrations, the sockets returned from ServerSocket.accept will all be unique. TCP already does that for you.
    If you haven't seen it yet be sure to check out [_The Java Networking Tutorial_|http://java.sun.com/docs/books/tutorial/networking/index.html]

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

  • I18n: having problems when sending accents through sockets

    Hi, I need help. I have to send a file, plain text whith accents. Say I have the following sentence in Spanish, "hace fr�o" (it's cold); when the server gets the file, what I get is: "hace fr?o".
    I'm using the following on the client side:
    PrintWriter os = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream(),
    "ISO-8859-1")),true);
    and the next one on the server side:
    is = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
    what am I doing wrong? I don't know whatelse I could try. I'm starting to think maybe it has to do with some configuration file in my machine (LINUX). Any idea?
    Thanks a lot!

    First of all, thanks a lot!
    It does work exporting LANG; however, it doesn't work using InputStreamReader and the charset.
      Reader fichProcesar = new InputStreamReader(new FileInputStream(args[0]), "ISO-8859-1");
      infich = new BufferedReader(fichProcesar);
       //env?o del fichero l?nea a l?nea hasta la l?nea FIN
       while (true) {
              String lineaProcesar = infich.readLine();
              System.out.println("Linea a enviar "+ lineaProcesar);
              os.println(lineaProcesar);
              if (lineaProcesar == null) break;
        }I don't want to bother you, but I prefer the option of using fixed encoding. It's
    "more portable".
    Could you tell me if I did something wrong, again, this time?
    Thanks a lot for your time.
    FileReader uses the platform's default encoding for
    reading the file. On a *nix system (like Linux) the
    default encoding depends on the locale settings; if
    you have not set the locale the default encoding is
    US-ASCII that doesn't support accented characters.
    You can either set up a locale that supports accented
    characters or use a fixed encoding for reading the
    file.
    A locale is simply set up by setting the environment
    variable LANG to some value, like "es_ES" for Spanish
    in Spain. If you use the bash shell the command you
    need is "export LANG=es_ES"
    To use a fixed encoding use FileInputStream with an
    InputStreamReader. For instance if the file is
    ISO-8859-1-encoded you'd use code like
    this:Reader fichProcesar = new
    InputStreamReader(new FileInputStream(args[0]),
    "ISO-8859-1");

  • Send a message through socket

    Hi
    I want to send a MIMEMessage through socket. And want to receive the same.
    Could any one help me out ?

    Hi
    I proceed that thing.
    I am getting the problem while converting the input stream from socket to MIME message.
    I am getting prob at following line.
      //soc is the object of Socket
      Session session =Session.getDefaultInstance(new Properties(), null);
      MimeMessage l_msg = new MimeMessage(session, soc.getInputStream());When I read the input stream from the file.
    It works successfully. But when I try to get it from socket not doesn't work.
    It's not showing any error also. So I am not able to track the actual error.
    Could you please tell me why it is not working.
    Thanks
    Anmolb

  • Getting Error while posting through KB11N : No true sender object entered

    HI Expert,
    We have stastical internal order defined and same we are using in Asset. Let me explain the scenarion.
    We created the Purchase requisition with the stastical Internal Order then we did Purchase Order and MIGO -Goods Receipt.
    Now we realised that wrong Internal Order  was used. Now we want to tranasfer cost from that Internal order to New Internal Order. we are trying to post through KB11N but while giving the all details i am getting error as per below;
    No true sender object entered
    Message no. BK175
    Diagnosis
    You have entered a statistical object as a sender. Statistical objects, however, are only intended for use with dual account assignments.
    Procedure
    1. If you require a dual account assignment, enter a true object as a sender also.
    We are using cost element with having cost element category 90.
    I don't no which is the true sender Object.
    Thanks in advance
    ealry help will be highly appreciated.

    Your postings had happened to a statistical internal order.  I hope the real postings might have happened to a cost centre.
    You cannot settle anything from a statistical internal order.  It is just for information purpose only.  If the above posting had captured a cost centre (real posting), you can distribute/assess the cost from the cost centre to a real internal order for your purpose.

  • 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

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

  • Send ArrayList through UDP socket

    I have the following 2D ArrayList
    ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();How is it possible to send it through a UDP socket and then get it back?

    Apart from adding implenents Serializable after the class name what else i have to do in order to add the arraylist to the datagramSocket?
    For simple sockets i have found this
    http://java.sun.com/developer/technicalArticles/ALT/sockets/ but
    but it doesn't work for DatagramSocket
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); throws an error "The method getOutputStream() is undefined for the type DatagramSocket"
    Edit: It seems this site has the solution
    http://www.nada.kth.se/~bishop/resources/javaSerial/index.html
    Message was edited by:
    [email protected]

Maybe you are looking for

  • F110 creates payment IDocs for all payments except the largest payment

    When executing a payment run, all payments are listed as successful.  However, one of the payments does not generate an IDoc to be sent to the bank.  (All other IDocs are successfully created)  No error message of any kind is generated and the paymen

  • Changing The Cursor

    {color:#993300}Hi Team I have one question when the move come to click on Button Icon my mouse cursor should be change, is it possible in oracle d2k 6i. Thanks{color} :8}

  • Why do former Windows Live accounts get spammed when updates are released?

    I still see only one person call live:[account name removed] and he started spamming me and I blocked him and it's still showing plz help I'm sad that this is happening and I want him to stop doing this to me This post was transferred from its previo

  • Getting following error when trying to run my application through eclipse

    Hi i am getting following error when i am trying to execute my program from my eclipse id 3.2 .Plz help me .I have also increase jvm memory upto 256M but it doesnt work. [java] E:\tarun\java\workspace1\Nss_Gui\main\build.xml:62: java.io.IOException:

  • Time Capsule 50 Device Limit Question/Help

    I have a Time Capsule and I understand they are limited to 50 devices.  Well, I must have reached my 50 device limit, because I can not connect any additonal devices.  How do I go about deleting past devices so newer devices can connect?  I've done a