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.

Similar Messages

  • How to know which user shutdown the server

    Hi,
    Is there a way to check which user has shutdown the server in windows server 2012.
    I know Event Id : 1076,1074,6008 gives information about system shutdown.but want to know which user did that ?
    thanks

    Steps to see which user shutdown the system:
    1. Go to event Viewer
    2. Right click on system and -> Filter Current Log
    3. For User Shutdowns, click downward arrow of Event Sources -> Check User32.
    4. In <All Event IDs> type  1074 -> OK
    This will give the list of Power off and restart events. It will have the date and time as well as Username.

  • How to detect client OS from SQL*Plus script

    Sometimes in a SQL*Plus script I need to execute OS commands e.g.
    host rm tempfile.bufHowever of course Windows has no "rm" command by default, so I have to edit the script to use
    host del tempfile.bufNow if I could define &DELETE (for example, "cat"/"type" is another) as a substitution variable, I could just use
    host &DELETE tempfile.bufMaybe I need more coffee but all I could come up with was something like this:
    def rm=rm
    def cat=cat
    spool sqlplus_windows_defs.cmd
    prompt echo def rm=del
    prompt echo def cat=type
    spool off
    host .\sqlplus_windows_defs > sqlplus_windows_defs.sql
    @sqlplus_windows_defs.sql
    host &rm sqlplus_windows_defs.cmd
    host &rm sqlplus_windows_defs.sqlthe idea being that you first define the variables for nix ("rm" and "cat"), then attempt to create and execute a Windows command file containing DOS versions ("dele" and "type"), which does not run under nix. Unfortunately the OS failure message (".sqlplus_windows_defs: not found" in Unix) appears on the screen despite SET TERM OFF, so I'm back where I started.
    I know there are various ways to get the server OS, and you can get the SQL*Plus version with &_SQLPLUS_RELEASE and so on, but I can't see a way to determine the client OS. Any suggestions?

    Thanks guys. This seems to work in Windows XP - will try on Unix when I get a chance:
    col DELETE_COMMAND new_value DELETE_COMMAND
    col LIST_COMMAND new_value LIST_COMMAND
    def list_command = TYPE
    def delete_command = DEL
    SELECT DECODE(os,'MSWIN','TYPE','cat') AS list_command
         , DECODE(os,'MSWIN','DEL','rm')   AS delete_command
    FROM   ( SELECT CASE WHEN UPPER(program) LIKE '%.EXE' THEN 'MSWIN' END AS os
             FROM   v$session
             WHERE  audsid = SYS_CONTEXT('userenv','sessionid') );
    host &LIST_COMMAND xplan_errors.lst
    host &DELETE_COMMAND xplan_errors.lstIf the user doesn't have access to v$session it will just default to the Windows commands.
    http://www.williamrobertson.net/code/xplan.sql

  • RMI How can a Client reconnect to a server after connection(any)-error

    I have the following problem:
    My RMI-Server runs for ever. In a batch-queue I have a procedure which looks periodly wether rmiregistry
    and RMI-Server exists. On error both processes are killed and restarted.
    My client as a simple example is displaying the server time. If any communication-problem with the
    server exists, I need an automatic reconnect to the server. I accept that into the time distanz of the
    error the display is frozen. Its unacceptable to restart the client !!.
    The following example demonstates my test-example:
    Server:
    1. Start
    2. waits for connecting (factory)
    3. answer time-requests
    Client:
    1. Start
    2. create a time class initially 1.jan.1970 00:00:00
    3. Start a timer displaying the time class every second
    4. start a timer connecting/reconnecting to the server and ask the servers actual time every second
    PS. Is the server to stubil programmed, so that a hang can exists?
    It would be nice, if anybody could answer me !!
    The following sources work correctly without solving the problem of the reconnect:
    ////////////// Echo.java
    package emi.server;
    import java.rmi.*;
    import java.util.*;
    public interface Echo
    extends Remote
    public Date getTime() throws RemoteException;
    ////////////// EchoClient.java
    package emi.server;
    //import emi.utility.basics.*;
    public class EchoClient
    public static void main(String args[]) throws Exception
    EchoClient echoclient1 = new EchoClient();
    //Check the argument count
    if (args.length != 1)
    System.err.println("Usage: EchoClient <server> --> EXIT");
    System.exit(0);
    // all of time relevant things
    Etim acttim = new Etim();
    // displaying continous the time
    EchoClientDisplay disp = new EchoClientDisplay(acttim);
    disp.StartTimer();
    // transfering continous the time from the server
    EchoClientTransfer trans = new EchoClientTransfer(acttim, args[0]);
    trans.StartTimer();
    ////////////// EchoClientDisplay.java
    package emi.server;
    import java.awt.event.*;
    import javax.swing.*;
    // displaying every 750 Milliseconds the value of the time
    public class EchoClientDisplay implements ActionListener
    private Timer tim;
    private Etim tact;
    public EchoClientDisplay(Etim tact)
    tim = new Timer(750, this);
    this.tact = tact;
    public void StartTimer()
    tim.setRepeats(true);
    tim.setInitialDelay(5);
    tim.start();
    public void actionPerformed(ActionEvent e )
    System.out.println(tact.toString());
    ////////////// EchoClientTransfer.java
    package emi.server;
    import java.rmi.Naming;
    import java.rmi.RMISecurityManager;
    import java.awt.event.*;
    import javax.swing.Timer;
    import java.util.Date;
    // transferring the actual time from the server
    public class EchoClientTransfer implements ActionListener
    private Etim tact;
    private String hostname;
    private Timer tim;
    private boolean init = false;
    private Echo echoRef1 = null;
    public EchoClientTransfer(Etim tact, String hostname)
    this.tact = tact;
    this.hostname = hostname;
    this.tim = new Timer(500, this);
    public void StartTimer()
    tim.setRepeats(true);
    tim.setInitialDelay(5);
    tim.start();
    public void actionPerformed(ActionEvent e )
    //>>>>>>>>>>> this construction doesnt work correctly, its only good until the first
    // network error
    try
    if( init == false )
    // Create and install the security manager
    System.setSecurityManager(new RMISecurityManager());
    //get the remote factory object from the registry
    String url = new String("rmi://"+ hostname +"/EchoFactory");
    EchoFactory remoteFactory = (EchoFactory)Naming.lookup(url);
    //get references to new EchoImpl instances
    echoRef1 = remoteFactory.getEcho("User Meyer");
    init = true;
    if( init = true )
    //make the remote calls
    Date d = echoRef1.getTime();
    tact.setDate(d);
    catch(Exception ee)
    System.out.println(ee.toString());
    init = false;
    //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    ////////////// EchoFactory.java
    package emi.server;
    import java.rmi.RemoteException;
    import java.rmi.Remote;
    public interface EchoFactory extends Remote
    Echo getEcho(String userName) throws RemoteException;
    ////////////// EchoFactoryImpl.java
    package emi.server;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class EchoFactoryImpl extends UnicastRemoteObject implements EchoFactory
    EchoFactoryImpl() throws RemoteException {};
    public Echo getEcho(String userName) throws RemoteException
    EchoImpl echoRef = new EchoImpl(userName);
    return (Echo)echoRef;
    ////////////// EchoImpl.java
    package emi.server;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import java.util.*;
    public class EchoImpl extends UnicastRemoteObject implements Echo
    private String userName;
    public EchoImpl() throws RemoteException
    public EchoImpl(String userName) throws RemoteException
    this.userName = userName;
    public Date getTime()
    Etim e = new Etim();
    e.setTimeAct();
    return e.get();
    ////////////// EchoServer.java
    package emi.server;
    import java.rmi.Naming;
    import java.rmi.RMISecurityManager;
    public class EchoServer
    public static void main(String args[]) throws Exception
    // Create and install the security manager
    System.setSecurityManager(new RMISecurityManager());
    // Create the servant instance for registration
    EchoFactory factoryRef = new EchoFactoryImpl();
    // Bind the object to the rmiregistry
    Naming.rebind("EchoFactory", factoryRef);
    System.out.println("Echo object ready and bound to the name 'EchoFactory'!");
    ////////////// Etim.java
    package emi.server;
    import java.util.*;
    import java.text.*;
    // this is my central class working up all time problems .. many hundred lines of code
    // I think, you must not look at this code ist setting and reading time
    // this is only a subset of methods for this example
    public class Etim
    private Date dat;
    private Calendar cal;
    public Etim()
    cal = Calendar.getInstance(); // Gregorianischer Kalender
    dat = new Date(0L); // January 1, 1970, 00:00:00
    cal.clear();
    * Zeit lesen.
    public Date get()
    return dat;
    // setting the time
    public void setDate( Date d )
    dat.setTime( d.getTime() );
    cal.setTime(dat);
    // gets my time-class to the current system-clock
    public void setTimeAct()
    long millis;
    millis = System.currentTimeMillis();
    setMilli(millis);
    * Zeit setzen.
    public void setMilli(long millis)
    dat.setTime(millis);
    cal.setTime(dat);
    // time in german format: day.month.year hour:minute:second:millisecond
    public String toString()
    return toStringTagMoJahr() + " " + toStringStdMiSek() +
    ":" + cal.get(Calendar.MILLISECOND);
    * Ausgabeformat Tag.Monat.Jahr (z.B. 01.01.2001).
    public String toStringTagMoJahr()
    SimpleDateFormat s = new SimpleDateFormat("dd.MM.yyyy");
    return s.format(dat);
    * Ausgabeformat Stunde:Minute:Sekunde (00:00:00 - 23:59:59).
    public String toStringStdMiSek()
    SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
    return s.format(dat);

    Hello willy51,
    Thank you for answering.
    I think, your comment of the design is true - its a problem when starting up in a new enviroment and
    you have nobody who shows you the right direction at the beginning. Talking personally together only
    10 minutes is better than writing a noval.
    I thing the following model of a client works better:
    concept:
    - visualize a personal time class continously evgery second
    - if there is a connection to a server set the time-class with the server time
    - if you loss connection, try to reconnect
    question:
    in which situation hangs connectToServer() ?
    (whithout the simple errors : no rmiregistry, no rmi-server)
    public class EchoClient
    private String hostname;
    public static void main(String args[]) throws Exception
    // my internal TIME-Class
    Etim acttim = new Etim();
    // Create and install the security manager
    System.setSecurityManager(new RMISecurityManager());
    // remote call
    Echo echoRef1 = null;
    String url = new String("rmi://"+ servername:port +"/EchoFactory");
    // displaying continous the time, technic = swing.timer
    EchoClientDisplay disp = new EchoClientDisplay(acttim);
    disp.StartTimer();
    // transfering continous the time from the server, technic = swing.timer
    // The state of transfer from server = offline
    EchoClientTransfer trans = new EchoClientTransfer(acttim);
    trans.StartTimer();
    // Connect to server
    connectToServer(url, echoRef1, trans);
    // wait for ever, if connection failed, try every 5 seconds a reconnect to server
    while(true)
    // test, if connection failed. The connections fails if the Object EchoClientTransfer
    // get a error, when it asks the server for the time ( remote call )
    if(trans.getStatus() == false ) // test, if connection failed
    connectToServer(url, echoRef1, trans);
    // try it again after 5 seconds
    Thread.sleep(5000);
    private static void connectToServer(String url, Echo echoRef1, EchoClientTransfer trans)
    System.out.println("Retry connection");
    // Connect to server
    while( true )
    try
    //get the remote factory object from the registry
    EchoFactory remoteFactory = (EchoFactory)Naming.lookup(url);
    //get references to new EchoImpl instances
    echoRef1 = remoteFactory.getEcho("User Meyer");
    // reactivate Datatransfer because I have now a new connection to the server
    trans.reactivateAfterConnectionError(echoRef1);
    // end of initialisation
    break;
    catch( Exception e )
    //>>>>>>> Error initialising connection to server. try again after 5 seconds"
    Thread.sleep(5000); // retry after 5 seconds

  • How to detect client's max screen size?

    I am using 2 functions right now, but I don't quite understand what they do.
    //Create and set up the window.
    frame = new JFrame("Test of TAN Books product database");
    frame.setBounds(30,30,1024,740);
    The main content pane is a table:
    table.setPreferredScrollableViewportSize(new Dimension(1024, 650));
    But if I set the latter to 1280 X 1024, the window becomes larger than my screen!
    How can I get it set to the MAX client window size?
    I'm willing to read up on this -- but I can't find that category on Sun's documentation.
    Matthew

    when in doubt, go to Google: http://www.google.com/search?q=java+screen+size
    Could have saved a lot of typing...
    Toolkit.getScreenSize()
    Message was edited by:
    Jaspre

  • How can an client-applet connect to server-DB?

    as the subject.
    I want the applet@client-side connect to DataBase@server-side,
    I am using Tomcat as engine & JDBC-mysql as tools
    where should the jdbc class placed in? WEB-INF/classes ? WEB-INF/lib ?? or others?
    now i am facing the problem that the applet seems cannot access WEB-INF and cannot locate the jdbc driver.
    could anybody give me some hints?
    thank you very much

    Hello
    I don't know the answer, sorry. This is the jdb (java debugger) tool forum.
    You might want to post your question over on the JDBC forum.
    Try this link:
    http://forum.java.sun.com/forum.jsp?forum=48

  • DHCP on 'hybrid' network - how to point clients to specific DHCP server

    Moving computers off of a private 'hybrid' network to a different private network.
    ISSUE: The clents will boot and ask for an IP from DHCP, problem is the 'hybrid' network runs a DHCP server with address range of 192.99.x.x  whereas the DHCP server we need to hit is on the 10.2.xx address range.  Is there a simple method to point
    clients to a specific DHCP server? 
    Note: I have requested Network Srvcs to block UDP traffice on ports 67 and 68 for the address range of the 'hybrid' network.
    Users still need access to the hybrid.
    Please advise,
    Many Thanks in advance

    DHCP is rather a simple minded service. The client broadcasts out and the first guy responds. If you ahve two DHCP servers on the same subnet or wire, even if they have different IP addresses on that subnet, and they both have scopes corresponding to
    the IP address of their interface on that subnet/wire, then they will offer DHCP services. DHCP won't give out an IP on an interface that the scope doesn't match the subnet.
    For example, if I have a DHCP server with an IP of 10.200.1.200/24, and a scope of 10.200.1.100-150/24, then it will give out IPs on that interface. However, if that same DHCP server has an interface configured with 192.168.20.150, then DHCP will not give
    out IPs on an interface configured with 10.200.1.100, unless there is a Relay Agent or IP Helper from the router or switch VLAN that is connected to that subnet. You can test this out yourself.
    A separate VLAN for each subnet solves the problem because you are separating the two servers to hostg DHCP on their own, respective subnets.
    Ace Fekay
    MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
    Microsoft Certified Trainer
    Microsoft MVP - Directory Services
    Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php
    This posting is provided AS-IS with no warranties or guarantees and confers no rights.

  • How can a client know the ip of the server?

    How can a client locate a rmi - server without
    have the ip of the server.
    Is there a methode that can check if there's a
    server in a L.a.n?

    We have used 2 different solutions.
    1. Our servers use UDP multicast and send out empty packets every second. The client listens on the multicast address:port, and once it sees a packet, it bootstraps the RMI object by contacting the registry on the server that sent the multicast.
    2. In another case we use JNLP/ Webstart to launch the client. With JNLP you can pass a parameter through to the app's System.properties via -D option on the command line using the jnlp property tag. If you change the ip address of the server you just update the *.jnlp file's particular <property> tag with the new value. The next time everyone launches the app, webstart will see that the *.jnlp has changed, will download the latest version of the jnlp file, decide it has all the correct jars etc, then launch the app with the new property value.
    This is a great way to centrally manage the configuration of multiple clients when the configuration is the same on all clients but might change over time.
    Bruce

  • File transfer to multiple clients from server socket

    I have multiple clients connected to my server socket and I need to copy more than 200mb documents from server to all clients over socket. Can we design the issue considering scalability and performance factor? What I am thinking of we should use thread for transferring file from server to client. But at the same time if we have large number of clients then we can't initialize a thread for each client. I think in this case we should initialize less than 10 threads in the pool as the file size is very large. If we keep number of threads in the pool low then probably we have to read multiple times the large server file (once for each group) which might again be a performance bottleneck. Please pour in your suggestions.

    File would be same for an instance only. For example say I have a "SEND File" button & �File Path� text box. In File Path suppose user enters the absolute path of the file and then clicks on Send File button. The responsibility of Send File button would be sending the file mentioned in the "File Path" text box to all connected client. But next time user can choose a different file.

  • Detecting client proxy settings

    Dear All,
    Can anyone tell me how to detect client proxy settings from a java application (not in a browser).
    I tried System.getProperties().getProperty("http.proxyhost") without success.
    Our application is distribuited using Java Web Start technology and needs to know proxy settings to connect to the remote host thru an unknown proxy server.
    Solution to this problem is very important and urgent! Please help me!
    Thanks in advance!

    Look for
    proxyHost
    proxyPort
    or (for https)
    https.proxyHost
    https.proxyPort

  • How to detect is response deliverred to the client?

    Hello everybody...
    I have problem and don't know how to solve.
    My server application runs on apache tomcat 5.5, and deals with some important data transactions.
    After getting the request, server has 5 sec. to send response, after that clients will close their sockets.
    The connection can be very slow, (GPRS), so it is very possible that transaction will not be over in that time.
    I need the way to find out, on my server side, when response isn't get to client in 5 sec.
    Is there any idea how to do that?
    Sorry if my English is not so perfect.
    Thanks

    Yes, but that way of write timeout means that write have 5 sec to send buffer to the underlying protocol.
    I can't know if TCP succeed or not to deliver data in that short time. I think write is asynchron.
    Problem is how to detect when client is disconnect and data are not delivered.
    Once again, sorry if my English is not so good.

  • Socket Exception when closing Server Socket Streams if Client closes first

    Hi
    I have 2 processes - a Server socket and a client socket. If I close the Client process first, and then try closing down the Streams on the Server process, I get a SocketException with message "Socket is closed" when I try and close the 2nd Stream. It does not matter on the order of the Stream being closed down, the exception is always thrown when I try and close the second stream. The code snippets are below:
    SERVER =======
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class ServerSocketTest {
    public static void main(String args[]) {
    try {
    ServerSocket ss = new ServerSocket(9999);
    Socket s = ss.accept();
    // Get refs to streams...
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    // sleep to let client shutdown first...
    try {
    Thread.sleep(10000);
    } catch (InterruptedException e) {
    System.err.println(e);
    System.err.println("B4 inClose: isBound=" + s.isBound());
    System.err.println("B4 inClose: isClosed=" + s.isClosed());
    System.err.println("B4 inClose: isConnected=" + s.isConnected());
    System.err.println("B4 inClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("B4 inClose: isOutputShutdown=" + s.isOutputShutdown());
    s.getInputStream().close();
    System.err.println("After inClose: isBound=" + s.isBound());
    System.err.println("After inClose: isClosed=" + s.isClosed());
    System.err.println("After inClose: isConnected=" + s.isConnected());
    System.err.println("After inClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("After inClose: isOutputShutdown=" + s.isOutputShutdown());
    s.getOutputStream().close(); // will break here with SocketException!
    System.err.println("After outClose: isBound=" + s.isBound());
    System.err.println("After outClose: isClosed=" + s.isClosed());
    System.err.println("After outClose: isConnected=" + s.isConnected());
    System.err.println("After outClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("After outClose: isOutputShutdown=" + s.isOutputShutdown());
    s.close();
    } catch (Exception e) {
    System.err.println(e);
    CLIENT ======
    import java.net.Socket;
    public class ClientSocket {
    public static void main(String args[]) {
    try {
    Socket s = new Socket("localhost", 9999);
    try {
    // sleep to leave connection up for a while...
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    System.err.println(e);
    s.close();
    } catch (Exception e) {
    System.err.println(e);
    The debug shows that isClosed() is set to 'true' after the first call to s.getInputStream().close(). The Sun API Socket class getOutputStream() has a call to isClosed() at the start of the method - it then throws the SocketException that I get. Why does the SocketImpl do this before I get a chance to call a.getOutputStream().close()?
    One final thing, the calls to s.isInputShutdown() and s.isOuputShutdown always seem to return false even if the Streams have had their .close() method called.
    Any ideas/help here greatly appreciated.
    Thanks
    Gaz

    Ok, I know what's going on now - I needed something to do on Friday afternoon anyhow!
    Basically if you call either getOutputStream.close() or getInputStream().close(), the underlying Sun implementation will close the Socket.
    Here's what's happening under the covers in the Sun code:
    s.getInputStream() is called on the Socket class.
    The Socket class holds a reference to the SocketImpl class.
    The SocketImpl class is abstract and forces sublclasses to extend it' s getInputStream() method.
    The PlainSocketImpl extends SocketImpl.
    PlainSocketImpl has a getInputStream() method that returns a SocketInputStream. When the stream is created for the first time, the PlainSocketImpl object is passed into the Constructor.
    The SocketInputStream class has a close() method on it. The snippet of code below shows how the socket is closed:
    <pre>
    * Closes the stream.
    private boolean closing = false;
    public void close() throws IOException {
         // Prevent recursion. See BugId 4484411
         if (closing)
         return;
         closing = true;
         if (socket != null) {
         if (!socket.isClosed())
              socket.close();
         } else
         impl.close();
         closing = false;
    </pre>
    So, it seems that out PlainSocketImpl is getting closed for us, hence the SocketException being thrown in Socket.getOutputStream() when I call it after Socket.getInputStream()/
    I've not had a look at the reason why the calls to s.isInputShutdown() and s.isOuputShutdown always seem to return false even if the Streams have had their .close() method called though - any thoughts appreciated.
    Thanks
    G

  • How to detect ipaddress client when computer client is turn on

    I have problem :
    ** how to detect ipaddress from client when the computer client is turn on???
    i have assumption : server ipaddress 192.168.2.21
    client_1 ipaddress 192.168.2.26
    client_2 ipaddress 192.168.2.27
    anyone want to help me,please give me the sample program.
    thanks before.

    your client will have to
    1) start up when the machine does
    2) make a TCP/IP connection to the server as it starts up
    when the server gets a connection from the client, you can query the relevant Socket object for the source IP address
    a simple 'google' for java socket tutorials, or a search of the Sun site will show you more quickly and definitively than anyone on a forum

  • How to make Client instantly recieve msg from Server

    Hello! I'm trying to make a multiplayer game via Bluetooth (RFCOMM protocol) in J2ME. I already managed to detect devices both as a client and as a server. I also managed to send real-time message from client(s) to server in the following way:
    // Pauses thread until Transmission occurs
    StreamConnection conn = notifier.acceptAndOpen();
    read_msg(conn); //this is the function which reads the date received from client
    But when I try the above as a client I got some exception, but never mind actually.
    Here is the actual problem:
    I want to be able to send a message from server to client whenever I press a key so that the client instantly receives that message.
    Now the only thing that comes to my mind is to periodically check (i.e. every 50 ms) StreamConnection and watch for some changes like this.
    while(true) {
    InputStream input = conn.openInputStream(); // conn is of type StreamConnection
    //now I check if the messege received is the new one OR have I actually received a message
    // here I pause the Thread for i.e. 60 ms
    But that would be extremely CPU heavy and foolish, wouldn't it?
    So is there a smart way to register when client gets a message from server?
    Please give me some example for client side.
    Edited by: leden on Sep 27, 2007 3:07 PM

    One more question.
    I have a server and many clients. Let's say I had already received the first message from every client with this piece of code:
    for(int current_client = 0; current_client < MAX_CLIENTS; ++current_client) {
    //notifier is of type StreamConnectionNotifier
    StreamConnection conn = notifier.acceptAndOpen(); //wait for transmission to occur
    String response = read_msg(conn); //read_msg actually reads the message
    Now, at some other moment I want to send a message to one of the clients .
    How could I do that?
    Do I have to add this command in the for loop above, perhaps?:
    conn_client[current_client] = conn;
    then simply reply by doing:
    OutputStream output = conn_list[who_I_want_to_send_msg_to].openOutputStream();
    and then the code like in my first post
    OR this whole procedure is totally wrong?
    Please explaim me what does openOutputStream() actually do?
    Edited by: leden on Sep 30, 2007 8:51 AM

  • How to get the user input while server is waiting for client's message

    I have a server/client program (using sockets)
    I used a thread to let a server always waiting for client's request, but how should I found that
    there is no message pass to server from client.
    public void run(){
    while (true){
    Socket server = serverP.accept();
    ObjectInputStream inFromClient = new ObjectInputStream(server.getInputStream());
    inMessage = (Message)inFromClient.readObject();
    System.out.println("Deadlock may occurred, please enter your command: ");
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    String command = inFromUser.readLine();
    The server is waiting for the inMessage that is passed from multiple clients. But if the server
    received no message after some time, it will assume something is wrong (eg, there is a
    deadlock), then it will ask the user to input the command to execute the method.
    If I put
    "System.out.println("Do you want to take Snapshot: ");
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    String command = inFromUser.readLine();"
    inside the while loop, it will keep asking user to enter the input when every time the client
    connect to the server. But I want to ask the user to enter the command only when the server
    can't get the response from clients.
    How should I do?
    Please help.

    Your statement:
    Socket server = serverP.accept();
    it will block until Server receive connect request from client.
    So, what u can do is, create a seperate Thread which check if server is idle (no client connect to it) for a certain time.
    public class xxxxx extends Thread {
    public void run(){
       (new WatcherThread()).start()
       while (true){
       Socket server = serverP.accept();
       WatcherThread.acceptFlag();  
       ObjectInputStream inFromClient = new ObjectInputStream(server.getInputStream());
       inMessage = (Message)inFromClient.readObject();
       Do something with client request ...
       I suggest you to create a WorkerThread for
       each client request.
       For example:
       new (WorkerThread(inMessage)).start();
       This way, your server thread will immediately serve
       the next client request ASAP.
    public class WatcherThread extends Thread {
       private static accept = false;
       public static void acceptFlag() {
            flag = true;
       public void run() {
           while(true) {
               try { sleep(10000); } catch (Exception ex) { }
               if (!accept) { // never accepted after 10000 msecs
                  ... do your System.in here ...
               flag=false;          
    }The idea is, your server notify WatcherThread if a client connect. WathcerThread runs at seperate thread. It waits for 10000 msecs and check if Server ever gets connect request from server. If it doesn't then you can do your System.in, otherwise, it will wait for 10000 again..
    FYI, next time, please use [ code ] and [ / code ] to format your code. It discourage me to read plain whole-left-aligned code like yours.
    See: http://forum.java.sun.com/features.jsp#Formatting
    rgds,
    Alex

Maybe you are looking for

  • Secure link to iTunes failed

    I use Firefox and have been unable to update iTunes. when running iTunes diagnostics, the Network Connectivy Test results say "Secure link to iTunes failed". Can someone help me here?

  • Embedding password prompting

    I have many protected directories created on the server side with my provider, it makes the browser pop up a window prompting the user for a username and password. it all works fine, but i dont like it. i would like for there to be just a username an

  • Proto sharing is useless

    Adobe should have explained in bold letters that proto files cannot be shared or viewed by others (clients). First of all, a client that gets a .pro extension can't do anything with it, which means wasting my time teaching each client how to change t

  • InDesign not appearing on menus following install

    InDesign not appearing on menus following install on Windows 7 and MAC.

  • File renamed to captions metadata

    I am in need of a way to rename files to the Caption metadata.