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?

Similar Messages

  • ObjectInputStream problems

    Hi
    I'm getting slightly desperate after 3 days stuck with the same problem.
    I'm writing a small client server application that contains a chat room. when I use a printwriter combined with a BufferedReader on the sockets everything works perfectly.
    However, I need to send objects to keep a state for some additinbal functionality, and when I change the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream I keep getting a StreamCorruptedException on the client.
    It goes like this. As long as I keep sending objects from the server, the client receives them well, but as soon as the server stop sending (waiting for som GUI interaction) I get the exception. As I understand it, the program is supposed to wait at the in.readUTF(); line and then continue when it receives data, but it doesn't wait. It just throws an exception as soon as it stops receiving data.
    I don't think it has anything to do with the read method. Apparently it is the ObjectInputStream complaing when receiving no data.
    Does anyone have an explanition for this?

    I'm not sure exactly how you're "changing the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream", but the problem is probably that you're sending binary data (ObjectOutputStream) into a text stream (PrintWriter). If you need to send both binary and text data, then I think you will have to set up two sets of streams.

  • ObjectInputStream problem.

    Hello!
    I have a problem with ObjectInputStream.
    My Servlet code is:
    public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
    When I call it, I get "The page cannot be displayed".
    But when I write
    InputStreamReader inputFromApplet = new InputStreamReader(request.getInputStream());
    instead, the page is displayed(showing nothing, of cause).
    It doesn't matter whether I call the servlet from applet or from browser. Anyway, here is a part of my Applet code:
    URL DownloadFileServlet = new URL( servletGET );
    URLConnection servletConnection = DownloadFileServlet.openConnection();
    // inform the connection that we will send output and accept input
    servletConnection.setDoInput(false);
    servletConnection.setDoOutput(true);
    // Don't use a cached version of URL connection.
    servletConnection.setUseCaches (false);
    servletConnection.setDefaultUseCaches (false);
    servletConnection.setRequestProperty
    ("Content-type", "application/octet-stream");
    ObjectOutputStream outputToServlet =
    new ObjectOutputStream(servletConnection.getOutputStream());
    String str = "abc";
    outputToServlet.writeObject(str);
    outputToServlet.flush();
    outputToServlet.close();
    Please help me.
    Thank you in advanse.

    Already posted in another forum.

  • Socket data send-receive problem

    I hv J2ME client application and vb.net socket server application communicating over sockets. Client connection is made successfully but cant send data to server. When I exit from client application then server application receives those data. (application works pretty fine on emulator but on real device gives above problem)
    WTK Sample application gives same problem when I tried.
    Any idea abt this problem ? gr8 ful if u have some working code.

    yeah your idea works..
    I hv used flush() method and now it works (Live on Nokia E62) nicely.
    But to keep connection opened during whole application I dont close InputStream/OutputStream connection. I close it only at EXIT of application so that I get optimum performace in transactions.

  • Sockets will not close problem

    Hi all,
    We have a cient/server system that handles many connections using a dynamic pool of sockets (grows to a maximum and shrinks when not in use) spawned from a ServerSocket. The clients come and go with great frequency. They connect, pass some info, and disconnect again. The protocol implemented is that when the client wants to disconnect, it tells the server that it is finished using one of the fields in the message, and the server does the disconnect. The server side code that reacts to such a request to disconnect is as follows (btw, this is nicely indented for real, but can't get it to look right here):
    try
    logger.log(3, "CLOSE CLIENT INPUT STREAM");
    if(client_input != null)
    client_input.close();
    client_input = null;
    } catch(Exception se)
    logger.log(0, "Input Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT OUTPUT STREAM");
    if(client_output != null)
    client_output.close();
    client_output = null;
    } catch(Exception se)
    logger.log(0, "Output Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT SOCKET");
    if(clientSocket != null)
    clientSocket.close();
    clientSocket = null;
    } catch(Exception se)
    logger.log(0, "Client Socket Close Error: "+ se);
    finally
    if(clientSocket != null)
    try
    clientSocket.close();
    clientSocket = null;
    } catch(Exception ex)
    {} // nothing can be done
    By far most of the times this works perfectly. The problem is this. With some clients only (it's a public internet app and we get all kinds of clients, and it's not always the same client type where this happens - i.e. sometimes Win2000 using JDK 1.3.1, sometimes another) the server reports through the logger that the socket is closed and everthing appears OK, but it didn't really close the socket! Running netstat shows those connections as still ESTABLISHED. With the amount of re-connecting these clients do, it only takes 2 or 3 such "ill behaved clients" and we soon run up to our stated "maximum" number of sockets for the pool, and everything comes to a grinding halt!
    Searched the forums and only found one (very old) topic similar to this, with no answer.
    So the question is: IS THERE ANY WAY TO REALLY FORCE THE CLOSING OF A SOCKET AT THE SERVER END?
    Any thoughts appreciated.
    thanks,
    glitch

    Reposted all, with code tags
    Hi all,
    We have a cient/server system that handles many
    connections using a dynamic pool of sockets (grows to
    a maximum and shrinks when not in use) spawned from a
    ServerSocket. The clients come and go with great
    frequency. They connect, pass some info, and
    disconnect again. The protocol implemented is that
    when the client wants to disconnect, it tells the
    server that it is finished using one of the fields in
    the message, and the server does the disconnect. The
    server side code that reacts to such a request to
    disconnect is as follows (btw, this is nicely indented
    for real, but can't get it to look right here):
    try
    logger.log(3, "CLOSE CLIENT INPUT STREAM");
    if(client_input != null)
    client_input.close();
    client_input = null;
    } catch(Exception se)
    logger.log(0, "Input Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT OUTPUT STREAM");
    if(client_output != null)
    client_output.close();
    client_output = null;
    } catch(Exception se)
    logger.log(0, "Output Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT SOCKET");
    if(clientSocket != null)
    clientSocket.close();
    clientSocket = null;
    } catch(Exception se)
    logger.log(0, "Client Socket Close Error: "+
    r: "+ se);
    finally
    if(clientSocket != null)
    try
    clientSocket.close();
    clientSocket = null;
    } catch(Exception ex)
    {} // nothing can be done
    >
    By far most of the times this works perfectly. The
    problem is this. With some clients only (it's a
    public internet app and we get all kinds of clients,
    and it's not always the same client type where this
    happens - i.e. sometimes Win2000 using JDK 1.3.1,
    sometimes another) the server reports through the
    logger that the socket is closed and everthing appears
    OK, but it didn't really close the socket! Running
    netstat shows those connections as still ESTABLISHED.
    With the amount of re-connecting these clients do, it
    only takes 2 or 3 such "ill behaved clients" and we
    soon run up to our stated "maximum" number of sockets
    for the pool, and everything comes to a grinding
    halt!
    Searched the forums and only found one (very old)
    topic similar to this, with no answer.
    So the question is: IS THERE ANY WAY TO REALLY FORCE
    THE CLOSING OF A SOCKET AT THE SERVER END?
    Any thoughts appreciated.
    thanks,
    glitch

  • Speed Issue with objectoutputstream and objectinputstream

    Hi all,
    I have serialized my resultset into a file on the harddisk and converted it back into resultset using below methods : -
    public void writeRS(ResultSet pRs) {
    try {
    crs = new CachedRowSetImpl();
    } catch (SQLException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    try {
    crs.populate(pRs);
    } catch (SQLException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    ObjectOutputStream outputStream = null;
    try {
    outputStream = new ObjectOutputStream(new FileOutputStream("c:/ABC.xml"));
    } catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    try {
    outputStream.writeObject(crs);
    } catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    try {
    outputStream.flush();
    } catch (IOException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    try {
    outputStream.close();
    } catch (IOException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    public void ReadRS() {
    ObjectInputStream ois = null;
    try {
    DataInputStream dis = null;
    try {
    dis = new DataInputStream(new BufferedInputStream(new FileInputStream(new File("c:/ABC.xml"))));
    } catch (FileNotFoundException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    ois = new ObjectInputStream(dis);
    try {
    ResultSet t_Rs = (ResultSet) ois.readObject();
    try {
    while (t_Rs.next()) {
    System.out.println(t_Rs.getString("name"));
    } catch (SQLException ex) {
    Logger.getLogger(SerializeRecords.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    ois.close();
    } catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    try {
    ois.close();
    } catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    It Runs Fine with small resultset but when it became bigger likewise, suppose it is having 50,000 records then reading and writing taking too much time. Can i reduce it??? if yes, then please tell me how??

    Iteration with same data took 7 secondsIs that iterating over the original ResultSet or the one you fetched from the file?
    And, if the former, again, what's the point? If fetching 50,000 records from the DB only takes 7 seconds why aren't you doing that? Why are you even contemplating writing them to a file and reading them back?
    And if the latter, it is your processing that is at fault, not serialization, or buffering.
    Can we set the buffer size of outputstream and inputstream ?? Sure, put a BufferedOutputStream between the FileOutputStream and the ObjectOutputStream, and similarly with BufferedInputStream. You can control the buffer sizes of both.
    But I haven't yet heard what the actual point is.

  • My ipod nano 6th gen can't be identified by any computer, but it can still be charged in a wall socket. what's the problem in here? :'(

    There's this time that my ipod nano 6th gen stopped from being recognized on any computer, i tried all trouble shooting stuff but none of them worked, can you give me any solutions? i'm pretty desperate.

    Are you using a Macintosh or Windows?
    -Zeph

  • One Server Multiple Clients

    Hello,
    This server code accepts only one client connection at a time. However, I have several lines that are specifically for the server to accept more than one client. What do I need to do in addition for the server to recognize that it can accept more than one client at a time?
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    import javax.swing.JFrame;
    public class ServerTest
       public static void main( String args[] )
          Server application = new Server();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          application.runServer();
    class Server extends JFrame
       private JTextField enterField;
       private JTextArea displayArea;
       private ObjectOutputStream output;
       private ObjectInputStream input;
       private ServerSocket server;
       private Socket connection;
       private int counter = 1;
       private ExecutorService serverExecutor;
       private MultiServer clients[];
       public Server()
          super( "Server" );
          enterField = new JTextField();
          enterField.setEditable( false );
          enterField.addActionListener(
             new ActionListener()
                public void actionPerformed( ActionEvent event )
                   sendData( event.getActionCommand() );
                   enterField.setText( "" );
          add( enterField, BorderLayout.NORTH );
          displayArea = new JTextArea();
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
          setSize( 300, 150 );
          setVisible( true );
       public void runServer()
          serverExecutor = Executors.newCachedThreadPool();
          try
             server = new ServerSocket( 12345, 100 );
             while ( true )
                try
                   waitForConnection();
                   getStreams();
                   processConnection();
                catch ( EOFException eofException )
                   displayMessage( "\nServer terminated connection" );
                finally
                   closeConnection();
                   counter++;
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void waitForConnection() throws IOException
          displayMessage( "Waiting for connection\n" );
          connection = server.accept(); 
          serverExecutor.execute( new MultiServer(server, connection));     
          displayMessage( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() );
       private void getStreams() throws IOException
          output = new ObjectOutputStream( connection.getOutputStream() );
          output.flush();
          input = new ObjectInputStream( connection.getInputStream() );
          displayMessage( "\nGot I/O streams\n" );
       private void processConnection() throws IOException
          String message = "Connection successful";
          sendData( message );
          setTextFieldEditable( true );
          serverExecutor.execute(new MultiServer(server, connection));
          do
             try
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
             catch ( ClassNotFoundException classNotFoundException )
                displayMessage( "\nUnknown object type received" );
          } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
       private void closeConnection()
          displayMessage( "\nTerminating connection\n" );
          setTextFieldEditable( false );
          try
             output.close();
             input.close();
             connection.close();
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void sendData( String message )
          try
             output.writeObject( "SERVER>>> " + message );
             output.flush();
             displayMessage( "\nSERVER>>> " + message );
          catch ( IOException ioException )
             displayArea.append( "\nError writing object" );
       private void displayMessage( final String messageToDisplay )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   displayArea.append( messageToDisplay );
       private void setTextFieldEditable( final boolean editable )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   enterField.setEditable( editable );
      class MultiServer extends Thread
      public MultiServer(ServerSocket servers, Socket connection)
          servers = server;
      public void run(){System.out.print("Yes");}
    }

    Check out the "Supporting Multiple Clients" bit here: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    Start a Thread for each client. I'd recommend you create a class:
    class Client
        Socket socket;
        ObjectOutputStream out;
        ObjectInputStream in;
        ...any other client-specific data you need...
        public void sendMessage(String s) { ...send to this client...; }
       ...any other client-specific methods you need...;
    }Create one of those when accept() gets a new connection, then start the thread for that client.
    You may want to keep a LinkedList that contains all the Client objects. E.g. if you want to send a message to all clients you'd loop over the LinkedList and send to each in turn. Synchronize the list appropriately. Removing clients from the list when they close down can be interesting :-) so be careful.

  • Some question on ETL

    Hi,
    I have created an ETL script as below
    CREATE TABLE ext_tbl_cust
    ID NVARCHAR2(50),
    NUMX NVARCHAR2(20),
    CUST_TYP_CD NVARCHAR2(20),
    CUST_CAT_CD NVARCHAR2(20),
    CUST_STS_CD NVARCHAR2(20)
    ORGANIZATION EXTERNAL
    TYPE ORACLE_LOADER
    DEFAULT DIRECTORY dataFile_dir
    ACCESS PARAMETERS
    RECORDS DELIMITED BY NEWLINE
    BADFILE badFile_dir:'badFile.bad'
    LOGFILE logFile_dir:'logFile.log'
    SKIP 1
    FIELDS
    ID position (1:10) integer external,
    NUMX position (11:30) integer external,
    CUST_TYP_CD position (31:40) integer external,
    CUST_CAT_CD position (41:50) integer external,
    CUST_STS_CD position (51:70) char
    LOCATION('TESTFIXWIDTH.TXT')
    PARALLEL 2
    REJECT LIMIT UNLIMITED;
    My questions is for the LOCATION clause, how could I specify it with dynamic value ? Could do something where the LOCATION clause to read all the files in the specify directory ?
    Please help if you know ? I have try few method and it's doesn't work.
    Thanks in advance.
    p/s: I not using the Tools to build the script.

    try this:
    public class test{
         Socket socket;
         ObjectOutputStream oos;
         ObjectInputStream ooi;
         public test(){
              socket = new Socket("123.123.123.123", 1111);
              oos = new ObjectOutputStream(socket.getOutputStream());
              ooi = new ObjectInputStream(socket.getInputStream());
         public void write(Object object){
              oos.writeObject(object);
         public Object read(){
              Object object = ois.readObject();
              return object;
         public void close(){
              socket.close();
    }

  • A GUI problem when using sockets

    I have a problem with Client.java. it creates a socket to connect to a serversocket. I do this through the method "runClient()" .
    the problem is that if I call runClient from an actionlistener add to a button. here the graphics of the window will disappear and you will be stuck for reading input (input.readObject())
    On the other hand , if you call runClient automatically from the class constructor "Client()" the program will work normally.
    can anybody give me a hint what's going on?
    Why does the program blocks in the first case for input?why not the second?
    //Client.java
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         private JButton connect;
         ObjectOutputStream output;
         ObjectInputStream input;
         String message = "";
         public Client()
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       sendData(e.getActionCommand());
              c.add(enter ,BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              connect = new JButton("Connect");
              connect.addActionListener(
                   new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       //TRY THIS . . it won't work
                                       //runclient();     
              c.add(connect, BorderLayout.EAST);
              setSize(400,300);
              show();
              //This works normally
              runClient();
         public void runClient()
              Socket client;
              try
                   display.setText("attempting to connect \n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"),3500);
                   display.append("connected to : " + client.getInetAddress().getHostName());
                   output = new ObjectOutputStream(client.getOutputStream());
                   output.flush();
                   input = new ObjectInputStream(client.getInputStream());
                   display.append("\nGot I/O streams\n");
                   String message = "Client>>> Connection successful";
                   output.writeObject(message);
                   output.flush();
                   enter.setEnabled(true);
                   //YOU WILL GET STUCK HERE
                   do
                        try
                             message = (String) input.readObject();
                             display.append("\n" + message);
                             display.setCaretPosition(display.getText().length());
                        catch(ClassNotFoundException cnf)
                             display.append("unknown error\n");
                   } while( !message.equals("SERVER>>> TERMINATE"));/**/     
                   display.append("\nClosing Connection");
                   input.close();     
                   output.close();
                   client.close();
              catch(EOFException eof)
                   System.out.println("Server terminated connection");
              catch(IOException io)
                   JOptionPane.showMessageDialog(this,io.getMessage(),"Server Error",JOptionPane.ERROR_MESSAGE);
         private void sendData(String s)
              try
                   message = s;
                   output.writeObject("CLIENT>>> " + s);
                   output.flush();
                   display.append("\nCLIENT>>>" + s);
                   enter.setText("");
              catch(IOException e)
                   display.append("\nERROR writing object");
    }

    The problem is that you can NOT access a method between classes unless the method is static.
    THIS IS WRONG!
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack.GoUpHill();
    }It is wrong because "private void GoUpHill()" is not declared as static.
    THIS IS CORRECT!
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack.GoUpHill();
    }Note that "private static void GoUpHill()" is declared as static. That will work, but it will give an error because "pale" is not declared static. Obviously, you're going to need to make all your objects static... or, you could do this:
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack jr = new Jack();
          jr.GoUpHill();
    }A new instance of the Jack class is made so you can use GoUpHill() at will. You don't need any static methods or objects if you use that method... but it might not always do what you want it do.

  • A problem with ObjectInputStream

    I am a coding newbe and I recently tried to write a very simple app - an engine to send and recive objects through the net. This is what i get:
    //Serwer class:
    import java.net.*;
    import java.io.*;
    public class Serwer {
    public Serwer() {
    try {
    ServerSocket serw = new ServerSocket(23);
    System.out.println("Server up and running");
    while (true) {
    Socket soc = serw.accept();
    Obsluga obs = new Obsluga(soc);
    obs.start();
    catch (Exception e) {
    System.out.println(e);
    public static void main(String[] args)
    Serwer serwer = new Serwer();
    class Obsluga extends Thread {
    private Socket soc;
    public Obsluga(Socket soc) {
    this.soc = soc;
    public void run() {
    try {
    System.out.println("Connected from: " + soc.getInetAddress());
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(soc.getOutputStream()));
    //ObjectInputStream in = new ObjectInputStream(
    //new BufferedInputStream(soc.getInputStream()));
    //Here's the problem
    int i = 1;
    while(i<100) {
    Ob obiekt = new Ob(i,"text");
    out.writeObject(obiekt);
    i++;
    out.close();
    catch (IOException ex) {
    ex.printStackTrace();
    class Ob implements Serializable {
    private int number;
    private String text;
    public Ob(int number, String text) {
    this.number = number;
    this.text = text;
    public Ob() {
    public int getNumber() {
    return number;
    public String getText() {
    return text;
    public void setNumber(int i) {
    number = i;
    public void setText(String s) {
    text = s;
    //Client class:
    import java.io.*;
    import java.net.Socket;
    public class Klient {
    public Klient() {
    public static void main(String[] args) {
    ObslugaKlienta obsK = new ObslugaKlienta();
    obsK.run();
    class ObslugaKlienta extends Thread {
    public ObslugaKlienta() {
    public void run() {
    Ob obiektIn = new Ob();
    try {
    Socket socket = new Socket("localhost", 23);
    ObjectInputStream in = new ObjectInputStream(
    new BufferedInputStream(socket.getInputStream()));
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(socket.getOutputStream()));
    while (true) {
    obiektIn = (Ob) in.readObject();
    System.out.println(obiektIn.getNumber());
    catch(Exception e) {
    System.out.println(e);
    class Ob implements Serializable {
    private int number;
    private String text;
    public Ob(int number, String text) {
    this.number = number;
    this.text = text;
    public Ob() {
    public int getNumber() {
    return number;
    public String getText() {
    return text;
    public void setNumber(int i) {
    number = i;
    public void setText(String s) {
    text = s;
    The server class simply creates 100 Objects Ob and sends them to waiting Client, which prints the field number from it. And this works.
    The problem is, in my Serwer class, if I try to start new InputStreamReader, to receive Objects Ob from Client, the app stops working. Even if I am not using it anywhere. (u have to uncomment the declaration to see it - where "here is the problem" statment is)
    I think I am missing some theory about sockets. Can anyone clear me with it? And give me a working solution, what should I correct in my code to have both client and server able to exchange Objects?
    Im using jdk 1.6, and running both apps from a single machine.
    Thank you in advance.

    Thank you for the reply.
    I reworked my app: I moved sending and receiving to different Threads, but still I can not manage to get output i wanted to. I get the SocketClosed Exception.
    Server:
    package pakiet;
    import pakiet.Send;
    import pakiet.Receive;
    import java.net.*;
    import java.io.*;
    public class Serwer {
    public Serwer() {
    try {
    ServerSocket serw = new ServerSocket(23);
    System.out.println("Server up and running");
    while (true) {
    Socket soc = serw.accept();
    Obsluga obs = new Obsluga(soc);
    obs.start();
    catch (Exception e) {
    System.out.println(e);
    public static void main(String[] args)
    Serwer serwer = new Serwer();
    class Obsluga extends Thread {
    private Socket soc;
    public Obsluga(Socket soc) {
    this.soc = soc;
    public void run() {
    System.out.println("Connection from: " + soc.getInetAddress());
    new Receive(soc).start();
    new Send(soc).start();
    Client:
    package pakiet;
    import pakiet.Send;
    import pakiet.Receive;
    import java.io.*;
    import java.net.Socket;
    public class Klient {
    public Klient() {}
    public static void main(String[] args) {
    ObslugaKlienta obsK = new ObslugaKlienta();
    obsK.start();
    class ObslugaKlienta extends Thread {
    public ObslugaKlienta() {}
    public void run() {
    try {
    Socket socket = new Socket("localhost", 23);
    new Receive(socket).start();
    new Send(socket).start();
    catch(Exception e) {
    System.out.println(e);
    Send:
    package pakiet;
    import java.io.BufferedOutputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    class Send extends Thread {
    Socket socket;
    public Send(Socket socket) {
    this.socket = socket;
    public void run() {
    try {
    System.out.println("Thread Send activated");
    ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(socket.getOutputStream()));
    int i = 1;
    while(i<10) {
    Ob obiekt = new Ob(i,"tekst");
    out.writeObject(obiekt);
    sleep(100);
    i++;
    catch(Exception e) {
    System.out.println(e);
    Receive:
    package pakiet;
    import java.io.BufferedInputStream;
    import java.io.ObjectInputStream;
    import java.net.Socket;
    class Receive extends Thread {
    Socket socket;
    public Receive(Socket socket) {
    this.socket = socket;
    public void run() {
    try {
    System.out.println("Thread Receive activated");
    ObjectInputStream in = new ObjectInputStream(
    new BufferedInputStream(socket.getInputStream()));
    int i = 1;
    while(i<10) {
    Ob obiekt = (Ob) in.readObject();
    System.out.println(obiekt.getNumber());
    sleep(500);
    i++;
    catch(Exception e) {
    System.out.println(e);
    My goal is to receive Ob numbers simultaneously in both server and client output window. Now i got massage in both client and sever that Thread Send and Receive is activated, but nothing happends afterwards.
    I know its a lot of code, so I bolded the parts I consider most important.

  • Performance problems with java sockets

    Hi ,
    I written a server class that simply writes the numbers and the client simply reads those numbers and prints them. When I run the both client and server on tha same machine there is no data loss found. But when I run the server on different machine than client I found heavy dataloss.(while theserver written numbers from 1-9000 the client is able read only 6000 plus). The data loss is increased when the data read from the server socket created by the VB application. Here with i am pasting the code snippet for the Server and the Client java files . Please help me in solving this problem.
    Client.java
    import java.net.*;
    import java.io.*;
    public class Client
         static Socket client = null;
         ObjectInputStream is = null;
         public Client() throws Exception
              client = new Socket("rajsekhar",3333);
              is = new ObjectInputStream (client.getInputStream());
              while(true){
                   Integer in = (Integer)is.readObject();
                   System.out.println(in.toString());
         public static void main(String[] args) throws Exception
              new Client();
    Server.java
    import java.net.*;
    import java.io.*;
    public class Server
         public static void main(String[] args) throws Exception
              ServerSocket server = null;
              server = new ServerSocket(3333);
              Socket s = server.accept();
              ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
              int i =1;
              while(true)
                   os.writeObject(new Integer(i));
                   System.out.println(i);
                   i++;
    please help me .
    thanks in advance,
    Sridhar Reddy .R

    Hi,
    Try putting os.flush() after doing the writting... I mean:
    os.writeObject(new Integer(i));
    os.flush();
    Good Luck!

  • Sockets problem

    Hi ,
    I written a server class that simply writes the numbers and the client simply reads those numbers and prints them. When I run the both client and server on tha same machine there is no data loss found. But when I run the server on different machine than client I found heavy dataloss.(while theserver written numbers from 1-9000 the client is able read only 6000 plus). The data loss is increased when the data read from the server socket created by the VB application. Here with i am pasting the code snippet for the Server and the Client java files . Please help me in solving this problem.
    Client.java
    import java.net.*;
    import java.io.*;
    public class Client
         static Socket client = null;
         ObjectInputStream is = null;
         public Client() throws Exception
              client = new Socket("rajsekhar",3333);
              is = new ObjectInputStream (client.getInputStream());
              while(true){
                   Integer in = (Integer)is.readObject();
                   System.out.println(in.toString());
         public static void main(String[] args) throws Exception
              new Client();
    Server.java
    import java.net.*;
    import java.io.*;
    public class Server
         public static void main(String[] args) throws Exception
              ServerSocket server = null;
              server = new ServerSocket(3333);
              Socket s = server.accept();
              ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
              int i =1;
              while(true)
                   os.writeObject(new Integer(i));
                   System.out.println(i);
                   i++;
    please help me .
    thanks in advance,
    Sridhar Reddy .R

    This has nothing to do with JSSE; please post in a more appropriate forum.

  • Socket + GZip Stream + Object Stream problem

    Hello,
    I've been having a problem with my threaded networked application. I want to send GZipped Objects over a socket, but the ObjectInputStream constructor blocks. I understand that it is waiting for header information from the corresponding ObjectOutputStream. I am sure that the socket connection has been established, and the ObjectOutputStream is constructed before the ObjectInputStream on the other end. The header information never seems to get to the other end.
    If I remove the Gzip filter stream, everything works great. I'm thinking that the Gzip stream is buffering the 4 bytes of header info, waiting for more data before actually compressing anything. I've tried flushing everything, to no help. I've tried finish()ing the Gzip stream, but that means I can't send my object payload. I've checked the buffers of all the stream objects and see the Object Stream's header in its buffer, but never seems to get into the GZIPOutputStream's buffer.
    Has anyone successfully used Object Stream > GZIP Stream > Socket Stream before?
    I'm not interested in examples that use file streams, since I get the impression that Gzip works fine with those (and maybe even designed only for those, not for sockets).
    Thanks for any help.
    Dave C

    Thanks. I see what I'm doing differently now. I was trying to send multiple objects over the gzip stream, not 1 at a time, finish(), and construct a new Gzip and Object output stream.
    Seems to work with a ByteArrayOutput/InputStream, now to try with a socket..

  • Problem with ObjectOutputStream

    Hi,
    I face a problem with the code below.
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\temp\\test.ser"));
    oos.writeObject("Object 1");
    oos.close();
    oos = new ObjectOutputStream(new FileOutputStream("c:\\temp\\test.ser", true));
    oos.writeObject("Object 2");
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\temp\\test.ser"));
    System.out.println(ois.readObject());
    System.out.println(ois.readObject());
    ois.close();
    The above code throws StreamCorruptedException during second readObject. If someone knows the reason behind this kindly respond.
    Regards,
    Sathyakumar S.

    The fundamental reason for why this happens is as follows: the number of stream instances used in writing the file is not the same as the number of stream instances used in reading it. Specifically, if you look at object serialization format in the spec you will see that the stream is always prefixed with a TX_MAGIC value. It is written by an output stream instance only once, regardless of how many objects you write into it. Similarly, it is expected to be read only once. If an input stream instance encounters TX_MAGIC in the middle of a stream, it will be flagged as a format error. These two actions take place in the constructors of ObjectOutputStream and ObjectInputStream, respectively.
    In your code snippet you write the data using 2 output stream instances but read it using 1 input stream instance. If you match these counts, your example will work. There are two ways:
    (a) either use 1 output stream instance:
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\temp\\test.ser"));
    oos.writeObject("Object 1");
    oos.writeObject("Object 2");
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\temp\\test.ser"));
    System.out.println(ois.readObject());
    System.out.println(ois.readObject());
    ois.close();(b) or use 2 input stream instances:
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\temp\\test.ser"));
    oos.writeObject("Object 1");
    oos.close();
    oos = new ObjectOutputStream(new FileOutputStream("c:\\temp\\test.ser", true));
    oos.writeObject("Object 2");
    oos.close();
    InputStream is = new FileInputStream("c:\\temp\\test.ser");
    ObjectInputStream ois = new ObjectInputStream(is);
    System.out.println(ois.readObject());
    ObjectInputStream ois = new ObjectInputStream(is);
    System.out.println(ois.readObject());
    ois.close();Either one will have the effect of matching the expected written and read formats precisely.
    Hope this provides more insight,
    Vlad.

Maybe you are looking for