ObjectOutputStream in Socket

Can I send a my defined object to another computer by the following code :
Socket socket=new ( xxx.......
try {
ObjectOutputStream objectOutputStream =new ObjectOutputStream (socket.getOutputStream);
objectOutputStream .writeObject(myObject);
} catch(Exception e){
e.printStackTrace();
There is "java.io.NotSerializableException" occur , how can I correct this problem ?

Hello!
The object that you are sending must implement Serializable, i.e.
class MyObject implements Serializable{

Similar Messages

  • ObjectOutputStream/ObjectInputStream/Socket Problem

    I make request on a server with socket connection.
    I want to use one socket open connection.
    So, I don't close the socket.
    This is like that :
    public void serverConnection()
    try
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    ObjectOutputStream objectOutStream = new ObjectOutputStream(out);
    objectOutStream.writeObject(configConnection);
    DataInputStream in = new DataInputStream(s.getInputStream());               
    ObjectInputStream objectInStream = new ObjectInputStream(in);
    arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();
    } catch (Exception e)
    valid = false;
    System.out.println("Error " + e);
    When I use this funtion more then one time with the same socket, the prorgam wait an the instruction :
    ObjectInputStream objectInStream = new ObjectInputStream(in);
    I use objectInStream.close() ...
    But it create an other problem : i lost the socket connection.
    What's the solution ?

    You don't need a new input stream for the same socket. You just need to read the data off of the original socket.
    DataInputStream in = new DataInputStream(s.getInputStream());
    ObjectInputStream objectInStream = new ObjectInputStream(in);The above code is fine. You need to loop through the code below until you are done with the socket. Then you close the socket. If you close the stream, you will close the underlying socket.
    arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();

  • Non-blocking SocketChannels

    I'm trying to learn how to use non-blocking socket channles, but I haven't found much info (nor luck) so far.
    To learn, I'm building a server and a client. The server accepts input from the clients and process it in only one thread. The clients should send Objects to the server, and the server process them and return the result also as an Object. For this, I'm trying to use ObjectOutputStream and ObjectInputStream.
    The problem I don't know how to solve is that the SocketChannel is in non-bolcking mode, so I can't use their input/output streams (I get a IllegalBlockingModeException). In the server process loop I can reconfigure the SocketChannel to blocking mode to be able to read the Object, but I can't configure it to non-blocking mode again because I get a CancelledKeyException.
    Does anyone know how to work with InputStreams and non-blocking channels? Or where to find more info about it?
    Here are the relevant part of the server code:
    Set ready = selector.selectedKeys();
    Iterator i = ready.iterator();
    while (i.hasNext()) {
       try {
          SelectionKey sk = i.next();
          i.remove();
          if (sk.isAcceptable()) {
             ServerSocketChannel ssc = (ServerSocketChannel)sk.channel();
             SocketChannel sc = ssc.accept();
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ);
          } else if (sk.isReadable()) {
             SocketChannel sc = (SocketChannel)sk.channel();
             // PROBLEM: If the channel is in non-blocking mode
             // I cannot use InputStreams
             sk.cancel();
             sc.configureBlocking(true);
             // Read the object sent by the client
             ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(sc));
             Object o = in.readObject();
             // PROBLEM: Can't put the channel back to non-blocking mode
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ); // CancelledKeyException
       } catch (...){
    }

    In my client, this is working fine:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    for (int i = 0; i < 30000; i++) {
       oos = new ObjectOutputStream(sc.socket().getOutputStream());
       oos.writeObject(object);
       oos.flush();
       ois = new ObjectInputStream(sc.socket().getInputStream());
       Object o = ois.readObject();
    }But trying to do it like this throws a StreamCorruptedException at the server side.
    ObjectOutputStream oos = new ObjectOutputStream(sc.socket().getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(sc.socket().getInputStream());
    for (int i = 0; i < 30000; i++) {
       oos.writeObject(object);
       oos.flush();
       Object o = ois.readObject();
    }Do you know why?

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

  • Need an example of server / client program with swing interface

    Hi!
    After a lot of trying i still haven't managed to create a server client program using swing components ...
    can someone write a mini application to demonstrate how this can be done?
    i would like to have a frame with a button a texField for input and a textAread for the output
    What i have in mind is the following ..
    say im the server
    i write something in the textField and then i press the button
    then the information written in the textFiled is passed to the client who shows it in his textArea
    The same thing goes on with the client (he can write something in his own textField and when he presses the button the info is passed at the
    server who puts it in his textArea) and vice versa.
    i have written many classes that trying unsuccessfully to do that ... below i show my last attempt ...
    I would appreciate if you could write a small application which it could to this.
    The whole idea is to create a turn based game ( i have implemented the game engine and graphics and i try to add the internet function)
    Here is the code ...( i would appreciate if you write a new code instead of trying to correct mine ( which i think it's impossible) in order to use it as a general example)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    *  In order to have a more gereral program instead of passing strings between the server
    *  and the client a pass an MyObjext object.  The MyObject class has an integer and a String
    *  (which is always the same) field . At the textField i write an integer number and i
    *  make a new MyObject which i want to pass to the server or the client and vice versa.
    *  The textArea shows the integer value of the MyObject which was passed from the server /client
    public class MyUserInterface extends JFrame {
         MyObject returnObject;
         JTextField myTextField;
         JTextArea te ;
         ClientGame cg;
         ServerGame sg;
          * used to determine if the current instance is running as a client or host
         boolean isHost;
         //The constructor of the client
         public MyUserInterface(ClientGame cg){
              this("Client");
              this.cg = cg;
              isHost = false;
         //The constructor of the server
         public MyUserInterface(ServerGame sg){
              this("Server");
              this.sg = sg;
              isHost = true;
         //The general constructor used both by client and server ..
         // it initializes the GUi components and add an actionListenr to the button
         public MyUserInterface(String str) {
              super(str);
              myTextField = new JTextField(2);
              te = new JTextArea();
              te.setPreferredSize(new Dimension(100,100));
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        try{
                             int a = Integer.parseInt(MyUserInterface.this.myTextField.getText());
                             System.out.println(a);   //used to control the flow of the program
                                  MyUserInterface.this.returnObject = new MyObject(a);
                             //sends the data
                             sendData();
                             //waiting for response...
                             getData();
                             catch(Exception ex){System.out.println("Error in the UI action command" +
                                                                ex.printStackTrace();}
              JPanel panel =  new JPanel(new FlowLayout());
              panel.add(okButton);
              panel.add(myTextField);
              panel.add(te);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         protected MyObject getReturnObject() {
              return returnObject;
         public void sendData(){
              new Thread(new Runnable() {
                   @Override
                   public void run() { 
                        if (!isHost)cg.sentData(returnObject);    //using the Servers out and in methods
                        else sg.sentData(returnObject);                    //using the Clients out and in methods
                        System.out.println("data sending");
         public MyObject getData(){
              MyObject obj;
              System.out.println("Retrieveing Data");
              if (!isHost)obj = (MyObject)cg.getData();
              else obj = (MyObject)sg.getData();
              System.out.println(" data retrieved  = "+ obj.getInt());  //just to control how the code flows
              te.setText(obj.getInt()+"");       
              return obj;
         public static void main(String[] args) {
              *Initiating the Server
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ServerGame sg = new ServerGame();
                        new MyUserInterface(sg);
              }).start();     
               * Initiating the Client
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ClientGame cg = new ClientGame("192.168.178.21");   //<----in case you run my code
                                                                          //..don't forget to change to your
                        new MyUserInterface(cg);                              //ip
              }).start();
    import java.io.*;
    import java.net.*;
    public class ClientGame {
         String ipAddress;
         Socket clientSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ClientGame(String ipAddress) {
              this.ipAddress = ipAddress;
              try {
                   System.out.println("Connecting To Host");
                 clientSocket = new Socket(InetAddress.getByName(ipAddress),4444);
                System.out.println("Host Found ...Io initializaton");
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
         public Object getData(){
              Object fromServer = null ;
              do{
                 try {
                      fromServer = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromServer==null);
              return fromServer;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                             out.writeObject(obj);
                        catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
              catch (IOException e){}
    public class ServerGame {
         ServerSocket serverSocket;
         Socket clientSocket;
         ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ServerGame() {
              try{
                   serverSocket = new ServerSocket(4444);
                   clientSocket = serverSocket.accept();
                   out =  new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
              catch(IOException e){System.out.println("IOException in ServerGame");}
         public Object getData(){
              Object fromClient = null ;
              do{
                 try {
                      fromClient = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromClient==null);
             return fromClient;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                   out.writeObject(obj);
              catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
                   serverSocket.close();
              catch (IOException e){}
         public static void main(String[] args) {
              new ServerGame();
    import java.io.Serializable;
    * this is a test object
    * it has a String field and a value
    *  The string is always the same but the integer value is defined in the constructor
    public class MyObject implements Serializable{
         private static final long serialVersionUID = 1L;
         String str;
         int myInt;
         MyObject(int a){
              str = "A String";
              myInt = a;
         public int getInt(){
              return myInt;
    }

    Pitelk wrote:
    I believe that a good code example can teach you things ;that you would need many days of searching; in no timeSo lets write one small example.. Ill help a little, but you do most of the work.
    jverd approach is deffenetly the way to go.
    jverd wrote:
    * Write a very small, simple Swing program with an input area, an output area, and a button. When you click the button, what's in the input area gets copied over to the output area.This part is partially done.
    * Write a very small, simple client/server program without Swing. It should just send a couple of hardcoded messages back and forth.And this part is for you(Pitelk) to continue on. I cannot say that this is the best way. or that its good in any way. I do however like to write my client/server programs like this. And perhaps, and hopefully, Ill learn something new from this as well.
    This is how far I got in about 10-20min..
    package client;
    * To be added;
    * A connect method. That connects the client to the server and
    * opens up both the receive and transmit streams. After doing that
    * the an instance of the ServerListener class should be made.
    * Also an disconnect method could be usable. But thats a later part.
    public class TestClass1 {
    package utils;
    import java.io.ObjectInputStream;
    import client.TestClass1;
    * This class is meant to be listening to all responses given from
    * the server to the client. After a have received data from the
    * server. It should be forwarded to the client, in this case
    * TestClass1.
    public class ServerListener implements Runnable {
         public ServerListener(ObjectInputStream in, TestClass1 tc) {
         @Override
         public void run() {
              while(true) {
    package server;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    * This class should handle all data sent to the server from the clients.
    class Server implements Runnable {
         private static List<ObjectOutputStream> outStreams = new ArrayList<ObjectOutputStream>();
         private Socket client = null;
         public Server(Socket client) {
              this.client = client;
         @Override
         public void run() {
              while(true) {
    * The meaning of this class is to listen for clients trying to connect
    * to the server. Once connection is achieved a new thread for that client
    * should be made to listen for data sent by the client to the server.
    public class ChatServer implements Runnable {
         @Override
         public void run() {
              while(true) {
    package utils;
    import java.io.Serializable;
    @SuppressWarnings("serial")
    public class MyObject implements Serializable {
         private String mssg;
         private String clientID;
         private String clientName;
         public MyObject(String mssg, String clientID, String clientName) {
              this.mssg = mssg;
              this.clientID = clientID;
              this.clientName = clientName;
         //Generate getters and setters..
    }Continue on this, and when you get into problems etc post them. Also show with a small regular basis how far you have gotten with each class or it might be seen as you have lost intresst and then this thread is dead.
    EDIT: I should probably also say that Im not more than a java novice, at the verry most. So I cannot guarantee that I alone will be able to solve all the problems that might occure during this. But Im gonna try and help with the future problems that may(most likely will) occure atleast(Trying to reserve my self incase of misserable failiure from me in this attempt).
    Edited by: prigas on Jul 7, 2008 1:47 AM

  • Object send using Serializable problem

    My broblem here is that client send an object throw a socket and make some update in the server and send the object back to client but it seem that there is a problem in the following code :
    in = new ObjectInputStream(clientSocket.getInputStream());
    out = new ObjectOutputStream(clientSocket.getOutputStream());
    in the clientTCP class and in connection class .. this problem that it seem that the server doesn't get the object send by the Client .. can any one help me ..
    This is the code for the object to be send:
    public class Msgmsg{
    private String type;
    private String cur1;
    private String cur2;
    private double value;
    Msgmsg(String type,String cur1,String cur2,double value){
    this.type=type;
    this.cur1=cur1;
    this.cur2=cur2;
    this.value=value;
    void setType (String type){this.type = type;}
    void setCur1 (String cur1){this.cur1=cur1;}
    void setCur2 (String cur2){this.cur2=cur2;}
    void setValue(double value){this.value=value;}
    String getType (){return type;}
    String getCur1 (){return cur1;}
    String getCur2 (){return cur2;}
    double getValue(){return value;}
    This is the code for TCPServer
    import java.net.*;
    import java.io.*;
    public class TCPServer implements Serializable{
    public static void main (String args[]){
    try{
    int serverPort =8080;
    ServerSocket listenSocket = new ServerSocket(serverPort);
    while(true){
    Socket clientSocket = listenSocket.accept();
    Connection c = new Connection(clientSocket);
    catch (IOException e){System.out.println("listen: "+e.getMessage());}
    This is the connection class
    import java.net.*;
    import java.io.*;
    class Connection extends Thread{
    ObjectInputStream in;
    ObjectOutputStream out;
    Socket clientSocket;
    public Connection (Socket aClientSocket){
    try{
    clientSocket = aClientSocket;
    in = new ObjectInputStream(clientSocket.getInputStream());
    out = new ObjectOutputStream(clientSocket.getOutputStream());
    this.start();
    catch (IOException e){System.out.println("Connection: "+e.getMessage());}
    public void run(){
    try{
    Msgmsg message =(Msgmsg) in.readObject();
    if (message.getType().equals("Request")){
    message.setType("Reply");
    if (message.getCur1().equals("Dollar")&&
    message.getCur1().equals("Dinar")){
    message.setCur1("Dinar");
    message.setCur2("Dollar");
    double changeValue = message.getValue();
    changeValue = changeValue * 71 / 100;
    message.setValue(changeValue);
    else
    if (message.getCur1().equals("Dinar")&&
    message.getCur1().equals("Dollar")){
    message.setCur1("Dinar");
    message.setCur2("Dollar");
    double changeValue = message.getValue();
    changeValue = changeValue * 100 / 71;
    message.setValue(changeValue);
    else {
    message.setCur1("Undefined Currency");
    message.setCur2("Undefined Currency");
    message.setValue(0);
    else{
    message.setType("Undefined Message");
    message.setCur1("Error Message");
    message.setCur2("Error Message");
    message.setValue(0);
    out.writeObject(message);
    out.flush();
    catch(EOFException e){System.out.println("EOF: "+e.getMessage());}
    catch(IOException e){System.out.println("IO "+e.getMessage());}
    catch(ClassNotFoundException e){System.out.println("Class: "+e.getMessage());}
    finally {
    try{
    clientSocket.close();
    catch(IOException e){/*close failed*/}
    This is the code for TCPClient
    import java.net.*;
    import java.io.*;
    public class TCPClient implements Serializable{
    public static void main (String args[]){
    Msgmsg message;
    Socket s = null;
    ObjectInputStream in;
    ObjectOutputStream out;
    try{
    message = new Msgmsg("Request","Dinar","Dollar",50.5);
    int serverPort = 8080;
    s = new Socket("localhost",serverPort);
    in = new ObjectInputStream(s.getInputStream());
    out = new ObjectOutputStream (s.getOutputStream());
    out.writeObject(message);
    out.flush();
    message = (Msgmsg)in.readObject();
    System.out.println("Recieved1: "+message.getType());
    System.out.println("Recieved2: "+message.getCur1());
    System.out.println("Recieved3: "+message.getCur2());
    System.out.println("Recieved4: "+message.getValue());
    catch(UnknownHostException e){System.out.println("Sock: "+e.getMessage());}
    catch(EOFException e){System.out.println("EOF: "+e.getMessage());}
    catch(IOException e){System.out.println("IO: "+e.getMessage());}
    catch(ClassNotFoundException e){System.out.println("Class: "+e.getMessage());}
    finally {
    if (s!=null)
    try{
    s.close();
    }catch (IOException e){System.out.println("Close: "+e.getMessage());}
    Thanks for ur time

    You need to create ObjectOutputStream first and
    flush() it before creating the ObjectInputStreamwhat the difference I work these clases like another clases I have but the problem here is difference .. coz Imake tracing but it couldn't reach the following code:
    in = new ObjectInputStream(s.getInputStream);
    out = new ObjectOutputStream(s.getOutputStream);

  • Client Server program using Applets for client

    Creating a client server program using Applets for the clients.
    Having problems distrubting the message from client to client
    using ObjectOutputStreams/ObjectInputSteams.
    I can connect each client to simple server and respond with by writting
    the i/o stream of each client but unable to communicate from client to client. If any one out there has in tips of creating a class of objectOutputStreams that holds a array of ObjectOutputStreams and then broadcasts the message to every client, it would be much appreciated
    Thanks.

    Cheers poop for your reply
    I never explained the problem properly. What it is I am trying to set up a Client Server program using Applets as the clients GUI. The problem is broadcasting the message to multiply client connnection(s).
    Below is code, each client can connect and send message to the server. The problems is broadcasting the message to every client connection. The every client can input a message but only the last connected client can receive the message?????? Thanks in advance..
    /*this my server class */
    import java.io.*;
    import java.net.*;
    public class Server extends JFrame
    private static final int ServerPort=8080;
    private static final int MaxClients=10;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage broadcastMessage;
    public void runServer()          
    BroadCastMessage broadcastMessage= new BroadCastMessage();
    try
    {  //connect to server
    ServerSocket s = new ServerSocket(ServerPort,MaxClients);
         //listen to port 5000 for new connections
         ///max is 25
         System.out.println("Server listening on port "+ServerPort);
    while (state.isProgramRunning())
         try
         /// sGUI.waitForConnection();//new line
         s.setSoTimeout(100);
         //enable times in server-socket
         while (true)     
         Socket incoming = s.accept();
         //wait and accept connnections from serverSocket
         //instance of the class,pases the new connection and message
         //spawn as a thread
         SocketConnection connection=new SocketConnection(incoming,broadcastMessage);
         Thread a = new Thread(connection); a.start();
         System.out.println(state.getConnectionCount()+"Connection received from :"+incoming.getInetAddress());
         catch(InterruptedIOException x){}
    while (state.getConnectionCount()>0);
    System.exit(0);
    }catch (IOException e){}
    public static void main(String[] args)
    Server s =new Server();
         s.runServer();
    /*this is my socket connection thread*/
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class SocketConnection implements Runnable
    private ObjectOutputStream out;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage passOnMessage;
    private Socket theConnection=null;
    private String Inmessage="";
    private int Ocount;
    public SocketConnection(Socket caller,BroadCastMessage broadcastMessage,Ocount)
    theConnection =caller;///(5000,n)
    Ocount=ncount;
    passOnMessage=broadcastMessage;
    public void run()
    try
    getStreams();
    processConnection();
    catch(Exception e)
    {String clientDetails=("connection from IP Address: "+theConnection.getInetAddress());}
    private synchronized void getStreams() throws IOException
    { //get streams to send and receive data
    //set up output buffer to send header information
    ///Ocount++;
    //create new objectoutputstream
    output=passOnMessage.getOutputObject(output,theConnection,Ocount);
    ///flush output buffer to send header info.
    Ocount++;
    //set up input stream for objects
    input =new ObjectInputStream(
    theConnection.getInputStream());
    System.out.print("\nGot I/O streams\n");
    private synchronized void processConnection()throws IOException
    //process connection with client
    String Outmessage =" count : "+status.getConnectionCount();
    //send connection successful message to client
         Outmessage=Outmessage+"SERVER>>>Connection successful";
         output.writeObject(Outmessage);
    output.flush();
    do ///process messages sent from client
         try
         Inmessage = (String) input.readObject();
         System.out.println(Inmessage);
         /* //while the connection is open each line
         that is passed from the client to the server
         is read in and is displayed*/
         messageDetails.setMessage(Inmessage);
         String CurrentMessage=messageDetails.getMessage();
         //output.writeObject(CurrentMessage);
         // output.flush();
         passOnMessage.FloodMessage(CurrentMessage);
         //sending out the message
    catch(ClassNotFoundException classNotFoundException){}
    }while (!Outmessage.equals("CLIENT>>>TERMINATE"));
    /*this my attempt at broadcasting the message to all clients
    my thinking was that you could create a array of objectoutputstreams
    which in turn could be broadcasted(bit confussed here)*/
    import java.io.*;
    import java.net.*;
    public class BroadCastMessage /// implements Runnable
    private int count;
    private String Inmessage="";
    private ObjectOutputStream temp=null;
    private ObjectOutputStream[] output = new ObjectOutputStream [12];
    //temp level of array of objects
    public BroadCastMessage()
    count=0;
    public synchronized void FloodMessage(String message) throws IOException
    System.out.print(count);
         for(int i=0;i<count+1;i++)
         try
    {  System.out.print(count);
         output[count].writeObject(message);
         output[count].flush();
         catch(IOException ioException)
    {ioException.printStackTrace();}
         notifyAll();
    public ObjectOutputStream getOutputObject(ObjectOutputStream out,Socket caller,int Ocount)
    try
    { temp = new ObjectOutputStream(caller.getOutputStream());
         AddObjectOutputStream(temp,Ocount);
    ////FloodMessage();
         catch(IOException ioException)
    {ioException.printStackTrace();}
    return temp;     
    public void AddObjectOutputStream(ObjectOutputStream out,int Ocount)
    { ///add new object to array
    count=Ocount;
    output[count]=out;
    System.out.print("\nthe number of output streams : "+count+"\n");
    }

  • Open an objectoutputstream and printwriter on socket

    I have the following code:
    public void openConnection(String ipAddress) throws ConnectException{
    try{
          client = new Socket(ipAddress, 2000);
         out = new PrintWriter(client.getOutputStream(), true);
          objectOut = new ObjectOutputStream(client.getOutputStream());
         in = new ObjectInputStream(client.getInputStream());
         catch(ConnectException e){
         //there is no securityservice on the other side
         throw new ConnectException();}
         catch(Exception e){
                   System.out.println("Error : " +e);
    * Method that sends a list of constraints to the peer service
    * @param: SecurityConstraintList list: the list of constraints that is being sent to the peer
    * @param: String origin: the IP address of the sender, the peer uses this to save the list
    public void sendConstraints(SecurityConstraintList list, String origin){
    try{     out.println(origin);
         out.println("list");
         out.flush();
         objectOut.writeObject(list);
         objectOut.flush();
         in.close();
         objectOut.close();
         out.close();
    catch(Exception e){
         System.out.println("Error : "+e.getMessage());
         }The problem is situated in the part where I first print a line to the printwriter and after an object to the objectoutputstream. On the server i get an exception, being OptionalDataException.
    I don't get what the problem is. The exception is thrown when he reads information that he didn't expected, but i don't see how this is possible? Part of the code on the serverside is:
    else{
         if( inputLine.equals("list") ){
         //it is a securityconstraintlist that is sent
         SecurityConstraintList list;
         list = (SecurityConstraintList)inObject.readObject();
         System.out.println("Saving list");
         AppliedConstraints con = new AppliedConstraints(origin,list);
    FileOutputStream fileOutputStream = new FileOutputStream(listFile);
    ObjectOutputStream objectOut = new ObjectOutputStream(fileOutputStream);     objectOut.writeObject(con);
         objectOut.flush();                    
         objectOut.close();
         fileOutputStream.close();
         }Is it not possible to open an objectoutputstream and printwriter on the same outputstream? If so, is there an (easy) way to work around this?
    Any help would be greatly appreciated.

    Not sure what you mean by this 'reading those line
    terminators' ? Could you clarify?In your code I see a 'out.println("list");' statement. This sends the following character over your socket -- 'l', 'i', 's', 't', '\r', '\n', where the last characters denote a carriage return and a new line character respectively. Suppose the receiving en of the socket happens to be a Mac, where a line terminator is implemented as a single '\r'. This leaves the following '\n' character unread and ready to be read by the ObjectInputStream, which, obviously, doesn't know how to handle primitive data like this (hence the OptionalDataException).
    Like I wrote before -- read those individual bytes and see what really is transmitted over that socket; there must be some spurious bytes in there ...
    kind regards,
    Jos

  • Socket ObjectOutputStream or ObjectInputStream problem?

    Hi all!
    I have a problem with sockets and ObjectInputStreams objects: The first time I write into the ObjectOutputStream, the other side (ObjectInputStream) receives the object, the second time the ObjectInputStream doesnt receive it and the third time I've got an exception in the ObjectOutputStream -->
    java.net.SocketException: Software caused connection abort: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    The objects Im working with are mouse events and here is my code :
    // using a Thread to send packets from a queue 
        public void run(){
             Package pck;
             while(connected){
                 pck = queue.pop();
                 if (pck!=null){
                     sendpck(pck, socketList);
    public void sendpck(Package pck , LinkedList<Socket> list){
            ObjectOutputStream oos = null;
            for(Socket sock: list){
                try {
                    oos = new ObjectOutputStream(sock.getOutputStream()); // 1st time sends, 2nd seems to send, 3rd Exception
                    oos.writeObject(pck);
                    oos.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
        }The other side code for listening:
    public void prepareListener(Socket socketClient){
            try {
                ois = new ObjectInputStream(socketClient.getInputStream());
            } catch (IOException e) {
                connected = false;
        public void run() {
            while(connected){
                try {
                    Package pack = (Package)ois.readObject();  // recieves only once,
                        // execute Mouse event
                } catch (IOException e) {
                    this.connected=false;
                } catch (ClassNotFoundException e) {
                    this.connected=false;
        }I have doubts because the prepareListener method is called from an static method and I dont know if that could be a problem:
        public static void connectService(Socket clientSocket){
            ClientThread listenerClient = new ClientThread();
            listenerClient.prepareListener(clientSocket);
            if (listenerClient.isConnected()){
                Thread myThread = new Thread(listenerClient);
                myThread.start();
        }I hope I was clear..... please I need your help....
    Thanks in advance
    Edited by: Pogasu on May 10, 2009 8:13 PM

    Thanks for answering!
    You were right, i was ignoring an exception on the client side: java.io.StreamCorruptedException: invalid type code: AC.
    I create one ObjectOutputStream for each socket from my socketlist each time i want to send and for listening doesnt the thread starts with an InputStream. As I Understand, my problem is that the InputStream has a connection only with one OutputStream and the next time i want to write something I create another OutputStream that isnt the original one. Am I right? What I should have is a list of created OutputStreams instead of sockets?

  • Socket and ObjectOutputStream

    I created an ObjectOutputStream from a socket.
    ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
    Is there any way to get the socket from this object sream?

    I agree with u. And also i dont really need the socket once i have created objectstreams from it.
    I have a ServerSocket which creates a socket the moment someone connects to it. From that socket I am creating object streams. After creating the streams I am passing on the values of the streams(both in and out) to a JFrame object which also implements Runnable. The problem is that my in stream is working here but not my out.
    But the in and out works in the calling method. So I wanted to find out what is the IP address to which my OUT in the thread is sending the object.

  • ObjectInputStream - ObjectOutputStream, socket problem

    Hello,
    I'm tring to send and receive some object between a client and a server application.
    When the client application send an object the server is stock.
    This is a part of the server code:
    try
    inObj = new ObjectInputStream(client.getInputStream()); /// here the server program is stock
         mes1 = (Message) inObj.readObject();
         System.out.println(mes1);
         out.println("end");
    catch (ClassNotFoundException e)
    e.printStackTrace();
    catch(IOException e)
         e.printStackTrace();
    The client code:
    try
         in=new BufferedReader(new InputStreamReader(soclu.getInputStream()));
         out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(soclu.getOutputStream())),true);
         outObj = new ObjectOutputStream(soclu.getOutputStream());
         out.print("Info");
         //          out.flush();
         outObj.writeObject(m1);
         outObj.flush();
         raspuns = in.readLine();
         System.out.println(raspuns);
         System.out.println("Closing the communication!");
         out.print("end");
         out.close();
         in.close();
         outObj.close();
         soclu.close();
    catch(IOException e)
         System.out.println("Problems Tx/Rx");
         e.printStackTrace();
    The class Message implements Serializable
    if there is somebody hwo cold help me I appreciate that.
    Thnak you,
    aclaudia1

    You should not be opening both a PrintWriter and an ObjectOutputStream on the same socket. You should use a single stream to do all the output on the socket.

  • Problem with socket object writing

    hi,
    I made this little programm , with a class point , a server and a client.
    I try to send via the socket several point object.
    If send differents objects ( with several new point(... )) it works fine , but if i send the same object changing only the properties it doesn't work. Changing are not applicate.
    Here is the code.
    // POINT
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
        private int x_;
        private int y_;
        private Color c_;
        public point(int x, int y, Color c) {
           x_=x;
           y_=y;
           c_=c;
        public int get_x() { return x_ ; }
        public int get_y() { return y_ ; }
        public void set_x(int x) { x_=x ; }
        public void set_y(int y) { y_=y ; }
        public Color get_color() { return c_ ; }
    // SERVER
    import java.io.*;
    import java.net.*;
    public class s {
        public s()
            try
                ServerSocket server = new java.net.ServerSocket(80);
                java.net.Socket client  = server.accept();
                ObjectInputStream Istream_ = new ObjectInputStream(client.getInputStream());
                ObjectOutputStream Ostream_ = new ObjectOutputStream(client.getOutputStream());
                for(int i=0;i<4;i++)
                    point p_read = (point)Istream_.readObject();
                    System.out.print("x="+p_read.get_x());
                    System.out.println(" y="+p_read.get_y());
             catch (Exception exception) { exception.printStackTrace(); }
        public static void main(String args[])
         s s_ = new s();
    // CLIENT
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class c {
        public c()
            try
                ipJDialog ipjd = new ipJDialog();
                String ip = ipjd.getvalue();
                Socket socket  = new Socket(ip,80);
                System.out.println("connection avec serveur reussi");
                ObjectOutputStream Ostream_ = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream Istream_ = new ObjectInputStream(socket.getInputStream());
                point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
             catch (Exception exception) {exception.printStackTrace();}
        public static void main(String args[])
         c c_ = new c();
    // DIALOG TO GET IP FROM INPUTBOX
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ipJDialog extends JDialog implements ActionListener {
        private String ip_;
        private JTextArea jta_;
        private JTextField jtf_;
        private JButton jb1_;
        public ipJDialog()
            this.getContentPane().setLayout(null);
            this.setTitle("Entrez l'IP du serveur");
            this.setSize(220,100);
            this.setModal(true);
            ip_= "localhost";
            jta_ = new JTextArea("IP du serveur :");
            jta_.setBounds(10,5, 90,20);
            jta_.setOpaque(false);
            jta_.setEditable(false);
            getContentPane().add(jta_);
            jtf_ = new JTextField();
            jtf_.setBounds(110,5, 90,20);
            jtf_.requestFocus();
            getContentPane().add(jtf_);
            jb1_ = new JButton("OK");
            jb1_.setBounds(10,30, 90,30);
            jb1_.addActionListener(this);
            getContentPane().add(jb1_);
            this.setVisible(true);
        public String getvalue() { return ip_ ; }
        public void actionPerformed(ActionEvent evt)
            String ChoixOption = evt.getActionCommand();
         if(ChoixOption.equals("OK"))
                ip_=jtf_.getText();
                this.setVisible(false);
    if I replace in client :
             point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
    by :
             point p = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p);
                p.set_x(20);
                p.set_x(22);
                Ostream_.writeObject(p);
                p.set_x(55);
                p.set_x(32);
                Ostream_.writeObject(p);
                p.set_x(14);
                p.set_x(88);
                Ostream_.writeObject(p);
    I doesn't work , i receive a point with 50,50 ( the first one ) four times ...If you can explain me me why and what can I do ...
    Thx.

    For ObjectOutputStream, multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. State of a object will be recorded so that the ObjectOutputStream doesn't writes the same object to the outputstream when the object was refered by multiple references. So, when you tried to write the same object agains into the ObjectOutputStream, the ObjectOutputStream doesn't write the object, but passed the as a reference to the outputstream... In this case, on the other side, the ObjectInputStream will receive this reference and it will return the reference of this object (which is previous created when this object was passed over on the 1st time). This caused the ObjectInputStream will return a "unchanged" object even your object have changed before you write it agains to the ObjectOutputStream.
    My explaination maybe not that good... hope you can understand... :)

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • How to use channel with sockets?

    Hello
    i am impleme3nted a sinple client/server application. The serv handles multiple connection via multithread(one thread per connection). Here is my code
    private void listen(int port) throws IOException {
    ss = new ServerSocket(port); // Create the ServerSocket
    System.out.println("Listening on " + ss);
    while (true) {
    Socket s = ss.accept(); // Grab the next incoming connection
    //s.setKeepAlive(true);
    System.out.println("Connection from " + s);
    // Create a DataOutputStream for writing data to the other side
    //dout = new ObjectOutputStream(s.getOutputStream());
    // dout.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
    Thread clientThread =new ServerThread(s); // Create a new thread for this
    clientThread.start();
    // connection
    My client and server exchange object(serializable). How can i change this in order to add the ServerSocketChannel feature so that one thread deals with many connection?
    thanks a lot
    sebastien

    Hi, yes i have seen that document
    but i don't really know how i cna use it to update my code with channel feature.
    how can we do, please provide me an update of my previously posted code. I would be so thankful.
    thanks a lot
    sebastien

  • Logical error with Sockets, not closing properly

    Hi again everybody, I am still in need of help it seems. I have been working on a way to transfer files from computer a to computer b but I cannot get the Sockets/Streams to work properly!
    The problem I keep getting is "IOException: java.net.SocketException: Software caused connection abort: socket write error"
    According to some threads in this forum its either because of a firewall blocking or because of an error such as the client trying to write to a stream that is closed in the other end ( or something like that, I cannot remember 100%).
    The thing is: I am only getting this the second time I try to send the file, the first time it works just fine.
    I can solve the problem by restarting the server (resetting the socket) after every time I send the file but that is not a solution, but merely a confirmation that I indeed have a bug.
    Can you please have a look at my code and point out where I missed something? I have been staring blindly at the code on and off for over a day now.
    CLIENT:
    import java.io.*;
    import java.net.*;
    * This is the FileSender class
    * Final version will take a File and Socket pointer
    * and send the file over the socket using the according handshake-protocol.
    * Current version opens it's own socket and can only send one File.
    * parameters:
    *  // File myFile, Socket mySocket <-- Final version goal
    *  String[] args  ()
    * @author Glader
    *     @version 1.2
    public class FileSender {
         private static Socket clientSocket = null;
    //     private static DataOutputStream output; <-- ver 1.0
         private static ObjectOutputStream output = null;
         private static FileInputStream file;
         private static BufferedReader input = null;
         private static final boolean DEBUG = true;
          * @param args
         public static void main(String[] args) {  // NOTE: REBUILD BEFORE FINAL!!!
              if(args.length != 1){
    //               throw new IllegalArgumentException("Error in FileSender: recieved " + args.length + " arguments, expected 2.");
                   System.err.println("Usage: Provide the method with ONE valid filepath/filename");
              else{
                   try{
                        if(DEBUG){ // <--- DEBUG BLOCK
                             if(input != null)
                                  System.out.println("input was not null at beginning of runtime!");
                             if(output != null)
                                  System.out.println("output was not null at beginning of runtime!");
                             if(clientSocket != null)
                                  System.out.println("clientSocket was not null at beginning of runtime!");
                   file = new FileInputStream(args[0]);
                   if(DEBUG){ // <---- DEBUG BLOCK
                        System.out.println("The following argument was entered: " + args[0]);
                             File myFile = new File(args[0]);
                             String sizeString = "";
                             long fileLength = myFile.length();
                             if(fileLength == 0){ // The file does not exist
                                  sizeString = "File does not exist";
                             }else if((fileLength / 1048576) != 0){ // The file is larger than 1Mb
                                  sizeString = "Filesize: " + (fileLength / 1048576) + " Mb";
                             }else if((fileLength / 1024) != 0){ // The file is larger than 1Kb
                                  sizeString = "Filesize: " + (fileLength / 1024) + " Kb";
                             }else{ // The file is larger than 1b
                                  sizeString = "Filesize: " + fileLength + " b";
                             System.out.println(sizeString);
                   send(file);
                   try{
                   input.close();
                   output.close();
                   clientSocket.close();
                   file.close();
                   }catch(IOException e){
                   catch(FileNotFoundException ex){
                        System.err.println("Error: No file was found at " + args[0] + " Double-check and try again.");
                   }finally{
                        try{
                        file.close();
                        }catch(IOException e){
                             //Nothing we can do
               * Send method
              private static void send(FileInputStream inFile){
              try{
                   clientSocket = new Socket("192.168.0.167", 2345);  //open a socket
                   input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // read what the server is saying
                   output = new ObjectOutputStream(clientSocket.getOutputStream());
                   if(DEBUG){  // <----- DEBUG BLOCK
                        String debugString = "";
                        if(input == null)
                             debugString += "input is null";
                        if(debugString.length() != 0)
                             debugString += ", ";
                        if(output == null)
                             debugString += "output is null";
                        if(debugString.length() == 0)
                             debugString += "input & output are OK";
                        System.out.println("status at start of 'send'-method: " + debugString);
                   if(clientSocket != null && inFile != null){
                        try{
                             long currentTime = System.currentTimeMillis();
                             boolean finished = false;
                             int flushTicker = 0;
                             int packetTicker = 0;
                             if(DEBUG){ // <--- DEBUG BLOCK
                                  System.out.println("packet-counter at " + packetTicker + " before sending data");
                             while(!finished){
                                  byte[] buffer = new byte[1024];
                                       if(flushTicker % 100 == 0) // clear cache, prevents OutOfMemory error
                                            output.reset();
                                       flushTicker++;
                                       packetTicker++;
                                       int bytesRead = inFile.read(buffer);
                                       if(bytesRead == -1){
                                            output.writeObject(new Packet(null, "finished", false, bytesRead));
                                            finished = true;
                                            output.flush();
                                       output.writeObject(new Packet(buffer, "", true, bytesRead));
                                       output.flush();
                             if(DEBUG) // <--- DEBUG BLOCK
                                  System.out.println("Number of packets sent: " + packetTicker);
                                  if(DEBUG){ // <---- DEBUG BLOCK
                                       // System.out.println("buffer contains: " + buffer.length + " bytes");
                                  long time = 0;
                                       if(DEBUG){
                                            time = ((System.currentTimeMillis() - currentTime)/1000);
                                       if(time == 0){// The operation took a very short time, cannot measure in seconds
                                            System.out.println("The operation took ~" + (System.currentTimeMillis() - currentTime) + " ms");
                                       }else{
                                       System.out.println( "The operation took " + time + " Seconds");
                             catch(UnknownHostException e){
                                  System.err.println("Trying to connect to unknown host: " + e);
                             catch(IOException e){
                                  System.err.println("IOException: " + e);
                   else{ // SOCKET OR FILE WERE NULL!
                        String result = "";
                        if(clientSocket == null){
                             result += "socket";
                        }else if(output == null){
                             result += "output";
                        }else if(input == null){
                             result += "input";
                        System.out.println("Error occured, " + result + " was null.");
              catch(UnknownHostException e){
                   System.err.println("Couldn't find the host");
                   try{
                   clientSocket.close();
                   }catch(IOException io){
                        //Nothing left to do
              catch(IOException e){
                   System.err.println("Couldn't get I/O from the connection");
              finally{
                   try{
                        if(clientSocket != null)
                             clientSocket.close();
                   }catch(IOException e){
                        //Nothing we can do
    }SERVER:
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    * This is the main class for listening to incoming connections
    * It listens to an incoming ObjectInputStream and is able to
    * follow user-specified commands to execute various methods.
    * @author Glader
    * @version 1.1
    public class FileListener {
         static Socket incoming = null; // Socket connection with the client
         static ServerSocket ss = null;
         static ObjectInputStream is; // Data recieved from the connection
         static OutputStream out = null; // talk back to the client
         static FileOutputStream fout;
         static String response;
         private static final boolean DEBUG = true;
          * @param args
         public static void main(String[] args) {
              int port = 2345;
              boolean finished = false;
              while(true){
                   try{ // Establish server socket
                        ss = new ServerSocket(port);
                        }catch(IOException e){
              try{ // Wait for a client to connect
                   incoming = ss.accept();
                   if(DEBUG){ // <--- DEBUG BLOCK
                        if(ss != null)
                             System.out.println("ObjectInputStream initialized");
                   try{ // Read Objects from the incoming Stream
                   is = new ObjectInputStream(incoming.getInputStream());
                   fout = new FileOutputStream(new File("min fil.avi"));
                   int packetTicker = 0;
                   while(!finished){ // read until there are no more packets incoming
                   Packet currentPacket = (Packet) is.readObject();
                   packetTicker++;               
                   String command = currentPacket.getCommand();
                   if(command.length() != 0){ // The client is telling us something
                        // Insert a checking loop for all possible commands from the client here
                        if(command.equals("initiating")){
                             OutputStream out = incoming.getOutputStream();
                             out.write(10); // 10 signals that the client is cleared to send.
                        if(command.equals("finished")){
                             finished = true;
                             if(DEBUG){ // <--- DEBUG BLOCK
                             System.out.println("Connection terminated, client said \"" + command + "\"");
                             System.out.println("Total amount of packets recieved: " + packetTicker);
                   if(currentPacket.containsFileData()){
                        if(currentPacket.amountOfData() == -1)
                             finished = true;
                        if(currentPacket.amountOfData() != 1024){ // Special handling for not entirely full packets
                                  fout.write(currentPacket.getFileData(), 0, currentPacket.amountOfData());
                        }else{
                        fout.write(currentPacket.getFileData());
                   fout.close();
                   is.close();
                   incoming.close();
                   catch(ClassNotFoundException ex){
                        System.err.println("Error when reading Packet: " + ex);
                   finally{
                        if(fout != null){
                             fout.close();
                        }if(is != null){
                             is.close();
                        }if(incoming != null){
                             incoming.close();
                        }if(out != null)
                             out.close();
              catch (IOException ex){
                   System.err.println("Error getting inputStream");
         

    Follow-up question, need more information to solve the problem:
    My server now uses a ObjectOutputStream to send packets to the client, which successfully reads them BUT:
    the problem still remains! I am still getting a "SocketException socket write error" the second time I use the sender!
    Right now this is what the send-method in FileSender looks like.
    (Look at "// Connection Loop" for the biggest change.)
    What am I doing wrong here?
              private static void send(FileInputStream inFile){
                   if(DEBUG) // <--- DEBUG BLOCK
                        System.out.println("Flag reached: Beginning of \"send\"");
              try{
                   clientSocket = new Socket("192.168.0.167", 2345);  //open a socket
                   output = new ObjectOutputStream(clientSocket.getOutputStream()); // Outgoing Packets to the server
                   if(DEBUG){  // <----- DEBUG BLOCK
                        String debugString = "";
                        if(input == null)
                             debugString += "input is null";  // Expected with current code
                        if(debugString.length() != 0)
                             debugString += ", ";
                        if(output == null)
                             debugString += "output is null";
                        if(debugString.length() == 0)
                             debugString += "input & output are OK";
                        System.out.println("status at start of 'send'-method: " + debugString);
                   if(clientSocket != null && inFile != null){
                        try{
                             long currentTime = System.currentTimeMillis();
                             boolean finished = false;
                             boolean accepted = false;
                             int flushTicker = 0;
                             int packetTicker = 0;
                             // Connection loop with 500ms timeout
                             input = new ObjectInputStream(clientSocket.getInputStream()); // Incoming Packets from the server
                             while((System.currentTimeMillis() - currentTime) <= 500){ // try connecting for 500ms
                                  output.writeObject(new Packet(null, "initiating", false, 0)); // send the first request Packet
                                  try{
                                  Packet currentPacket = (Packet) input.readObject();
                                  String command = currentPacket.getCommand();
                                  if(DEBUG) // <--- DEBUG BLOCK
                                       System.out.println("Command sent from Server: " + command);
                                  if(command.equals("ready")){
                                       accepted = true;
                                  if(accepted){
                             while(!finished){
                                  byte[] buffer = new byte[1024];
                                       if(flushTicker % 100 == 0) // clear cache, prevents OutOfMemory error
                                            output.reset();
                                       flushTicker++;
                                       packetTicker++;
                                       int bytesRead = inFile.read(buffer);
                                       if(bytesRead == -1){
                                            output.writeObject(new Packet(null, "finished", false, bytesRead));
                                            finished = true;
                                            output.flush();
                                       output.writeObject(new Packet(buffer, "", true, bytesRead));
                                       output.flush();
                             catch(ClassNotFoundException e){
                                  System.err.println("ClassNotFoundException: " + e);
                                  while(bytesRead != -1){
                                  if(DEBUG) // <--- DEBUG BLOCK
                                       System.out.println("bytesRead: " + bytesRead);
                                  else{
                                  output.writeObject(new Packet(buffer, "", true));
                                  flushTicker++;
                                  if(bytesRead == -1){ // no more bytes to be read from the file
                                  long time = 0;
                                       if(DEBUG){
                                            System.out.println("Number of packets sent: " + packetTicker);
                                            time = ((System.currentTimeMillis() - currentTime)/1000);
                                       if(time == 0){// The operation took a very short time, cannot measure in seconds
                                            System.out.println("The operation took ~" + (System.currentTimeMillis() - currentTime) + " ms");
                                       }else{
                                       System.out.println( "The operation took " + time + " Seconds");
                             catch(UnknownHostException e){
                                  System.err.println("Trying to connect to unknown host: " + e);
                             catch(IOException e){
                                  System.err.println("IOException: " + e);
                   else{ // SOCKET OR FILE WERE NULL!
                        String result = "";
                        if(clientSocket == null){
                             result += "socket";
                        }else if(output == null){
                             result += "output";
                        }else if(input == null){
                             result += "input";
                        System.out.println("Error occured, " + result + " was null.");
              catch(UnknownHostException e){
                   System.err.println("Couldn't find the host");
                   try{
                   clientSocket.close();
                   }catch(IOException io){
                        //Nothing left to do
              catch(IOException e){
                   System.err.println("Couldn't get I/O from the connection");
              finally{
                   try{
                        if(clientSocket != null)
                             clientSocket.close();
                   }catch(IOException e){
                        //Nothing we can do
              }

Maybe you are looking for

  • Creatiing new document in TextEdit and saving it to a folder

    I'm just starting with applescript. I would like to write a script that will open an e-mail, copy the contents to a new TextEdit or TexShop file, and save the new document to a particular folder. Ultimately the name of the new document should depend

  • Schduling background jobs not showing in sm37

    Hi,   I scheduled the  jobs : Z_MM_INVENTORY_REPORT, RM07MLBS on daily basis from 03/22/2011.Its running successfully upto 03/26/2011 daily,after that when iam checking on SM37 from 03/27/2011 to 03/31/2011 it showing schduled on 03/27/2011 not runni

  • Adding a Webdynpro Abap custom application to the list HCM F&P List

    Hi On my Portal's  HR Admin tab i have a link Start process to start all my HCMF&P Processes. Is there any way i can add my custom web dynpro application to this list. So that using the same link the HR Can proces any Adobe Form or a custom web dynpr

  • Has Anyone Disassembled the new Zen y

    Haven't found anything on the net yet. I'm really interested to see what it looks like inside. I got one myself but havent found a way to open it without scratching or break it yet. Searching on the web for it is kind of hard, because of its name "ZE

  • No 3D

    dont see 3D in workspace pannel for cs6 extended trial version...am i alone