Socket closing before server can readObject()

I am trying to create a multi-threaded client server application that transmits objects. At the moment, I am having a hard time getting the sockets to coincide.
I start my server and wait for a connection:
ServerSocket ss = new ServerSocket(port_num);
Socket s = ss.accept();Then I create a new socket in the client to connect to the server:
Socket cs = new Socket("localhost", 8888);When the server class gets the connection, it creates a thread with the socket:
new DrawThread(s);The thread constructor creates an Input stream:
ois = new ObjectInputStream(sock.getInputStream());After the client creates the connection, it creates and ObjectOutputStream and writes my object:
oos = new ObjectOutputStream(cs.getOutputStream());
oos.writeObject(objects.get(0).getShape());Meanwhile in the run() method of the thread, we try to read it:
ois.readObject();However at this point I get an IOException because the client function was done and had exited so the socket was closed.
Any Idea what I can do to combat this problem? Full code for my client function, server and thread classes are below.
Client function:
   public void serverSave(){
        Date d = new Date();
        try{
        //initialize class network and IO vars
        Socket cs = new Socket("localhost", 8888);//create server
        oos = new ObjectOutputStream(cs.getOutputStream());
         //write the objects to the server
           // for(int i = 0; i< objects.size(); i++){
                 oos.writeObject(objects.get(0).getShape());
            //}//end for
       catch (UnknownHostException uhe){System.out.println("client uhe");System.out.println(uhe.getMessage());}
     catch(IOException ioe){System.out.println("client ioe");System.out.println(ioe.getMessage());}
     finally{
                //print out time to see when the function exits
          System.out.println(d.getTime());
   }Server Class:
import java.io.*;
import java.net.*;
class DrawServer{
     static int port_num = 8888;//default port number
     public void DrawServer(){}
     public static void main(String args[])throws IOException{
          //don't forget to close socket
          ServerSocket ss = new ServerSocket(port_num);
          while(true){
               System.out.println("begin listening");
               //blocking wait for a connection
               Socket s = ss.accept();
               //create new thread for the client
               new DrawThread(s);
               System.out.println("end listening");
               s.close();
          }//end while
     }//end main
}Thread Class
import java.net.*;
import java.net.Socket;
import java.io.*;
import java.util.*;
class DrawThread extends Thread{
     private Socket sock;
     private ObjectInputStream ois = null;
        private ObjectOutputStream oos = null;
        ObjectOutputStream out = null;
        //create a file input stream or buffered stream to accept filename from client???
     public DrawThread(Socket s){
          sock = s;
          try{
          ois = new ObjectInputStream(sock.getInputStream());
                oos = new ObjectOutputStream(sock.getOutputStream());
          start();
          catch( IOException ioe){}
     public void run(){
          Date d = new Date();
          System.out.println("Thread started");
          try{
          int i = 0;
          while(true){
               System.out.println("getting item " + ++i);
               ois.readObject();
          catch(FileNotFoundException fnfe){System.out.println("fnfe");}
          catch(IOException ioe){System.out.println("ioe     " + + d.getTime());System.out.println(ioe.getMessage());}
          catch(ClassNotFoundException cnfe){System.out.println("cnfe");}
          finally{
               try{out.close();}
               catch(IOException ioe2){System.out.println("ioe2");}
          System.out.println("Thread ending");
}Thanks,
Shannon

You have one problem with your DrawServer class:               new DrawThread(s); // this starts a thread that uses the socket
               System.out.println("end listening");
               s.close(); // this will close the socket while it is used in the DrawThread thread.Instead close the socket in the finally block of the DrawThread run() method (no need to close the ObjectOutputStream in that block).
Also since you are passing a variable number of objects between the client and the server
you should create a custom made protocol for both your ends to always be in sync with each other.
For instance the client could send first the number of objects to be sent,
then loop for this exact number and send the objects,
then upon receiving the server response close its socket.
The server could read for the number of objects to read,
then loop for the exact number and read the objects,
then send a response and close its socket.

Similar Messages

  • Firefox will not open, try to reinstall and message states firefox must be closed before install can begin.

    firefox will not open. when i try to reinstall firefox the process stops. the message tells me to close firefox before i can proceed. but firefox is not running.

    Prez,
    I too have had this problem a few times with several different versions of FF.
    What you need to do is to open a window to Task Manager (Ctrl-Alt-Del) and on the 'Processes' tab look down the list for Firefox, highlight the entry, then click "End Process". Accept the warning that pops up. You should then be able to uninstall.

  • Remote desktop connection manager on windows 8.1, can't connect to windows server 2012 R2, Socket closed

    remote desktop connection manager on windows 8.1, can't connect to windows server 2012 R2, Socket closed each time i try to open remote connection to the server,
    does remote desktop connection manager V2.2 not compatible with windows 8.1, and if so, is there are any other compatible versions
    or what's the problem,
    Mahmoud Sabry IT System Engineer

    this issue maybe will be fix by latest version, we still waiting for it
    maybe your issue can be fix using this methods
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/61f218a5-5ef8-49da-a035-90cdd64fc9a0/problem-with-remote-desktop-connection-manager-error-3334?forum=winserverTS
    http://shawn.meunier.com/?p=1#comment-43

  • The last few days I have been constantly saving my file. About an hour ago I opened my file and the most recent work wasn't saved even though I'm sure I saved it before closing. What can I do? Also, when I have tried to email it to myself as a backup, the

    The last few days I have been constantly saving my file. A couple of hours ago I renamed the file and then reopened my file a little while later, but the most recent work wasn't saved even though I'm sure I saved it before closing. What can I do? Also, when I have tried to email it to myself as a backup, the fields aren't populated when I open it up. Fyi, I have the free subscription.

    Hi Constance,
    As i understand your changes in the pdf were not saved...Are you still facing this issue?
    Regards,
    Rahul

  • How can I make my adodc connect faster to my SQL Server? It's taking a minute (so long) before I can view thousand of record in my listview.

    How can I make my adodc connect faster to my SQL Server? It's taking a minute (so long) before I can view thousand of record in my listview. Please anyone help me.
    I'm using this code:
    Public Class McheckpaymentNew
    Private cn As New ADODB.Connection
    Private rs As New ADODB.Recordset
    Private Sub McheckpaymentNew_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
    cn.ConnectionString = "DSN=database; UID=user; PWD=password"
    cn.Open()
    rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
    rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
    rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
    Catch ex As Exception
    MsgBox("Failed to Connect!, Please check your Network Connections, or Contact MIS Dept. for assistance.", vbCritical, "Error while Connecting to Database.."
    End
    End Try
    End Sub
    End Class

    How can I make my adodc connect faster to my SQL Server? It's taking a minute (so long) before I can view thousand of record in my listview. Please anyone help me.
    I'm using this code:
    Public Class McheckpaymentNew
    Private cn As New ADODB.Connection
    Private rs As New ADODB.Recordset
    Private Sub McheckpaymentNew_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
    cn.ConnectionString = "DSN=database; UID=user; PWD=password"
    cn.Open()
    rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
    rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
    rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
    Catch ex As Exception
    MsgBox("Failed to Connect!, Please check your Network Connections, or Contact MIS Dept. for assistance.", vbCritical, "Error while Connecting to Database.."
    End
    End Try
    End Sub
    End Class

  • SSRS Log shows Reporting web server started, was it closed before?

    Hi there:
        During the weekend, one of our sql jobs that calls  a RSS script to create a SSRS PDF report failed
        The job error says
        " Could not connect to server: http://XXXXXXXXX/ReportServer/ReportService2005.asmx "
        The command inside the job is below
        RS.EXE -i "\\XXXXXXXXX\Secure\Business Intelligence\SSRS\Scripts\publishReportSnapshot(366).rss" -s http://XXXXXXXXX/ReportServer -l 300
     (XXXXXXX refers to the server name which is withheld here)
     I've checked the SSRS log file and below is what I've found
    Please see the entries below:
    library!WindowsService_4!26e8!09/24/2011-12:18:07:: i INFO: Call to CleanBatch() ends
    library!WindowsService_4!15b8!09/24/2011-12:28:07:: i INFO: Call to CleanBatch()
    library!WindowsService_4!15b8!09/24/2011-12:28:07:: i INFO: Cleaned 0 batch records, 0 policies, 0 sessions, 0 cache entries, 0 snapshots, 0 chunks, 0 running jobs, 0 persisted streams, 0 segments, 0 segment mappings.
    library!WindowsService_4!15b8!09/24/2011-12:28:07:: i INFO: Call to CleanBatch() ends 
    appdomainmanager!DefaultDomain!2430!09/24/2011-12:36:20:: i INFO: Appdomain:15 ReportServer_MSSQLSERVER_0-9-129613665780462239 started.
    appdomainmanager!ReportServer_0-9!2430!09/24/2011-12:36:21:: i INFO: RS authentication mode is 4; effective ASP.NET authentication mode is Windows. vdir=/ReportServer.
    appdomainmanager!DefaultDomain!2430!09/24/2011-12:36:21:: i INFO: Appdomain:15 ReportServer_MSSQLSERVER_0-9-129613665780462239 initialized (#5).
    webserver!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Reporting Web Server started
    resourceutilities!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Reporting Services starting SKU: Enterprise
    resourceutilities!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Evaluation copy: 0 days left
    resourceutilities!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Running on 8 physical processors, 8 logical processors
    runningjobs!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Running Requests Scavenger timer enabled: Next Event: 60 seconds.  Cycle: 60 seconds
    runningjobs!ReportServer_0-9!2430!09/24/2011-12:37:31:: i INFO: Running Requests DB timer enabled: Next Event: 60 seconds.  Cycle: 60 seconds
    My question is as follows:
    1. Why does it have the entry saying Reporting web server started? Does it mean it was closed before?
    2.Why does it have the entry saying Evaluation copy: 0 days left
    thanks
     Hui--Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

    Hi cat_a,
    Please check the “SecureConnectionLevel” property value in the rsreportserver.config file. (By default, the rsreportserver.config file store in the following path:
    <drive:> Program Files\Microsoft SQL Server\ MSRS10.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config)
    When the value is set, the SecureConnectionLevel element in the report server configuration file is changed, and the URLRoot element in the configuration file is set to use "https://" if the specified Level is greater than or equal to 1, or "http://" if
    the specified Level is 0.
    For more information, please refer to the article below:
    http://msdn.microsoft.com/en-us/library/ms152810.aspx
    For the Report Server is Evaluation, there is a thread about this topic, please see:
    http://social.msdn.microsoft.com/Forums/en/sqlreportingservices/thread/02aa072e-905e-4e5a-b612-98df146fe3b1
    Thanks,
    Bin Long
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • I login in ftp server, but my session will be closed very soon, can i change the ftp session time in mozila?

    I login in my ftp server by use of Mozila browser, but my session will be closed very soon, can i change the ftp session time in mozila?

    Do you mean you browse the FTP server in a tab? That usually works for anonymous FTP downloading, but if your server requires a login, it might not work well because Firefox doesn't do anything special to keep the session alive.
    Would you consider using an add-on such as FireFTP? It's a traditional FTP client that runs in a tab.
    https://addons.mozilla.org/firefox/addon/fireftp/

  • I am running snow leopard, do i have to buy lion first before i can download lion server?

    i am running snow leopard, do i have to buy lion first before i can download lion server?

    Snow Leopard client or Snow Leopard Server ?

  • HT1349 before i do updates for my iphone(to 5.0.1) i close my SIM card, i can not complete the update proccess  becouse SIM is closed also i can not activate iPhone becous the SIM must be opened. when i try to open it , the networks does not appear (no se

    before i do updates for my iphone (to 5.0.1) i close my SIM card, i can not complete the update proccess  becouse SIM is closed also i can not  activate iPhone becouse the SIM must be opened. when i try to open it , the networks does not appear (no service).

    Its a serious problem and many people are facing the same issue on both locked and factory unlocked phones.
    I wonder when Apple will address to this issue. After all it is losing all its reputation!
    See this thread, many users are encountering the same issue:
    https://discussions.apple.com/thread/3425746?start=75&tstart=0
    I believe its a software issue and could be solved asap Apple fixes it!

  • I purchased Adobe Creative Suite 3 Master Collection Design Across Media Upgrade for Windows at a business closing.  What do I need to find out before I can use it?

    I purchased Adobe Creative Suite 3 Master Collection Design Across Media Upgrade for Windows at a business closing.  What do I need to find out before I can use it?

    I couldn't tell you what you purchased, and it might even be difficult for an Adobe employee to do so.  The business could have a few options as far as what they might have purchased.
    Your best bet, considering what little you paid, will be to hand it over to someone you might sell it to and let them try it out.  If it works, then it works.

  • ON/OFF BUTTON CANNOT FUNCTION...MUST PLUG IN TO SOCKET BEFORE IPAD CAN START

    Hi can anyone help me in this...Ive got the latest ipad gen 4 since last nov...recently unable to on/off using the on/off button.I need to plug into socket of using use to connect to pc before I can on my ipad...anybody any suggestion...
    Tks

    Tks Philly went to Apple service centre about my ipad problem....send in and 1 day later they ask me to go and collect a New ipad...he he
    Regards

  • Can I get back a pages document which I closed before saving?

    can I get back a pages document which I closed before saving?

    The answer is no, even if you're using OS X Lion. (You don't mention what version of OS X or Pages you use.)
    OS X Lion and Pages 4.1 autosave documents, even unsaved documents. But if you close an unsaved document, click the Don't Save button, then this document no longer exists.
    Earlier versions of OS X and Pages do not autosave documents. So closing an unsaved document effectively deletes it.

  • InitialDirContext Throwing ServiceUnavailableException socket closed

    Any assistance is appreciated.
    Problems occurring when multiple DirContext instances are created. Attempting to make a SSL connection to Active Directory on port 636. A single successful context can be established in the below code. However, a second instantiation of InitialDirContext(env) results in a javax.naming.ServiceUnavailableException: [domain]:636; socket closed error. Multiple contexts are desired to establish a connection pool.
    A few items to note. Establishing four unsecure DirContext on port 389 works successfully. I can establish a DirContext on port 636, use the context, close the context then establish new contexts without a problem. A server certificate was imported to the C:\j2sdk1.4.2_11\jre\lib\security\cacerts file. Testing on a local computer. Below is sample code:
    public static void main(String[] args) {
        try {
            System.setProperty("javax.net.debug","all");
            // Set up the environment for creating the initial context
            Hashtable env = new Hashtable();
             env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_PRINCIPAL, "[USER DN]");
            env.put(Context.SECURITY_CREDENTIALS, "[PWD]");
            //NON SSL
            //env.put(Context.PROVIDER_URL, "ldap://[server]:389");
            //SSL
            env.put(Context.PROVIDER_URL, "ldap://[server]:636");
            env.put(Context.SECURITY_PROTOCOL, "ssl");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            // Create the initial context
            DirContext ctx = null;
            DirContext ctx2 = null;
            DirContext ctx3 = null;
            DirContext ctx4 = null;
            try {
                //Works every time...
                ctx = new InitialDirContext(env);
            } catch (NamingException e) {
                e.printStackTrace();
            try {
            //Fails on port 636, works on port 389
            ctx2 = new InitialDirContext(env);
            } catch (NamingException e) {
                e.printStackTrace(); 
            try {
            //Works on port 636 (after 2nd attempt fails) and port 389
            ctx3 = new InitialDirContext(env);
            } catch (NamingException e) {
                e.printStackTrace();
            try {
            //Fails on port 636, works on port 389
            ctx4 = new InitialDirContext(env);
            } catch (NamingException e) {
                e.printStackTrace();
            Attributes attrs = ctx.getAttributes("[A USER DN]");
            System.out.println("Total attributes returned: " + attrs.size());
            try {
                ctx.close();
                ctx2.close();
                ctx3.close();
                ctx4.close();
            } catch (NamingException e) {
                e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        System.exit(0);
    }The java debug statements at the second exception:
    Thread-1, WRITE: TLSv1 Handshake, length = 121
    Thread-1, received EOFException: ignored
    Thread-1, called closeInternal(false)
    Thread-1, SEND TLSv1 ALERT:  warning, description = close_notify
    Plaintext before ENCRYPTION:  len = 18
    0000: 01 00 0F 78 84 EE 16 24   F6 99 B0 83 52 14 FF 86  ...x...$....R...
    0010: 29 3C                                              )<
    Thread-1, WRITE: TLSv1 Alert, length = 18
    Thread-1, called close()
    Thread-1, called closeInternal(true)Again, any assistance is appreciated.

    Multiple contexts are desired to establish a connection pool.The JNDI LDAP provider already does connection pooling so you don't need multiple initial contexts at all.

  • How to detect client socket shutdowns in server socket

    Hi,
    Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    try{
              if (serverSocket == null){
                    serverSocket = new ServerSocket(4511);
         clientSocket = serverSocket.accept();
         System.out.println("Accepted client request ... ");
         out = new PrintWriter(clientSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         System.out.println("Input / Output streams intialized ...");          
         while (true){                              
              System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
              System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
              System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
              System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
              System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
              System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
              System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
              messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
              //get Message from Queue Head (also removes it)
              message = getQueueMessage(messageQueue);
              //format and send to Third Party System
              if (message != null){
                             out.println(formatMessage(message));
                   System.out.println("Sent to Client... ");
              //sleep
              System.out.println("Going to sleep 5 sec");
              Thread.sleep(5000);
              System.out.println("Wake up ...");
    }catch(IOException ioe){
         System.out.println("initSocketServer::IOException : " + ioe.getMessage());
    }catch(Exception e){
         System.out.println("initSocketServer::Exception : " + e.getMessage());
    }I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
    Is Client Socket Closed : false
    Is Client Socket Connected : true
    Is Client Socket Bound : true
    Is Client Socket Input Shutdown : false
    Is Client Socket Output Shutdown : false
    Is Server Socket Bound : true
    Is Server Socket Closed : false
    So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
    Appreciate much, thanks.

    Crossposted and answered.

  • Socket closed exception

    Hi all,
    I am trying to execute an XI scenario in which i am sending data from sap R/3 system to a table in Oracle 8.0 system using JDBC adapter.
    The XI server has JDBC 9.0 driver.
    On sending the message, status shown on the XI server is successful, but no data is getting posted in the table.
    In XI runtime workbench, in component monitoring, the error shown with the JDBC driver is SOCKET CLOSED.
    Pls if anybody can help me with this problem.
    Its very urgent.
    Thanks in advance.
    Regards
    Neetu

    Hi,
    The error shown in the Adapter Monitor in Runtime Workbench is:
    Receiver Adapter v1027 for Party '', Service 'HURES':
    Configured at 16:35:07 2006-05-12
    Last message processing started 15:16:02 2006-05-13, Error: Transform error in xml processor class, rollback:
    ERROR:Processing request: Error when executing statement for table/stored proc. 'sap_promotion': java.sql.SQLException: Io exception: Socket closed
         at com.sap.aii.adapter.jdbc.xml2sql.service(xml2sql.java:175)
         at com.sap.aii.adapter.jdbc.XI2JDBC.onInternalMessage(XI2JDBC.java:266)
         at com.sap.aii.adapter.jdbc.SapAdapterServiceFrameImpl.callSapAdapter_i(SapAdapterServiceFrameImpl.java:170)
         at com.sap.aii.adapter.jdbc.SapAdapterServiceFrameImpl.callSapAdapter(SapAdapterServiceFrameImpl.java:146)
         at com.sap.aii.af.modules.CallAdapterWithMessageBean.process_receiver(CallAdapterWithMessageBean.java:206)
         at com.sap.aii.af.modules.CallAdapterWithMessageBean.process(CallAdapterWithMessageBean.java:161)
         at com.sap.aii.af.mp.module.ModuleLocalLocalObjectImpl1.process(ModuleLocalLocalObjectImpl1.java:103)
         at com.sap.aii.af.mp.ejb.ModuleProcessorBean.process(ModuleProcessorBean.java:221)
         at com.sap.aii.af.mp.processor.ModuleProcessorLocalLocalObjectImpl0.process(ModuleProcessorLocalLocalObjectImpl0.java:103)
         at com.sap.aii.af.listener.AFWListenerBean.onMessage(AFWListenerBean.java:216)
         at com.sap.aii.af.listener.AFWListenerLocalObjectImpl0.onMessage(AFWListenerLocalObjectImpl0.java:103)
         at com.sap.aii.af.ra.ms.impl.ServicesImpl.deliver(ServicesImpl.java:262)
         at com.sap.aii.adapter.xi.ms.XIEventHandler.onDeliver(XIEventHandler.java:611)
         at com.sap.aii.af.ra.ms.impl.core.queue.ReceiveConsumer.invokeHandler(ReceiveConsumer.java:353)
         at com.sap.aii.af.ra.ms.impl.core.queue.ReceiveConsumer.onMessage(ReceiveConsumer.java:98)
         at com.sap.aii.af.ra.ms.impl.core.queue.Queue.run(Queue.java:419)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:94)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:162)
    Regards
    Neetu

Maybe you are looking for