About Socket.isClosed or getOutputStream

Hi !
I'm working with a client connected with TCP on a server, using a Socket...
The server is restarted, ... while the client is not reading or writing from/to socket.
Is this possible after that, on client side, the Socket.isClosed() and the Socket.getOutputStream are working well (no exception throwed) but a SocketException when writing on outputstream ?
Thanks
Ludovic

When you write data to the output stream, it is buffered by the OS, bundled up using the nader algorithim and sent as a packet, then the packet is rejected by the server it is sent to (or times out) then the client knows the server has disconnected. You might have sent a significant amount of data before all this happens, and there is not much you can do except.
Read from getInputStream() and wait for an expected reply or an IOException. This will let you know of a success or failure.

Similar Messages

  • Where can I find everything about sockets?

    hi,
    i want to know everything about sockets (TCP), above all about all possible exceptions and when they are thrown. Until now, I can programm a normal chat programm. But sometimes I got problems with the sockets and then I solve them and I dont really know why. For example, it looks for me that if an outputstream of a socket is closed, the socket itself is closed. Well, I just need more infos about sockets, their streams, and exceptions (or maybe a good FAQ).
    thanx

    MmM you open them you close them and the rest is history.You use maltithreads with them but that depends on what you are doing.Also you might want to check out orb (Object request brokers) if you are wanting to do high level of network programming that deals with alot of clients.
    Also look into OMG (Object Manaement Group)and cobra
    Just a few thoughts if you are intrested in network programming.I take it you are since you are wanting to know all you can about sockets.
    Good luck

  • I have a question about socket

    I've got a socket question that haven't to work out for two days . If you know something about this question please give me a hand , Thank you .............
    ===================================================
    I want to write a program about PortMapping with Java.
    It means : put one port's data to another port .
    =============================
    Just like :
    There is a Tomcat Web Server listener on the 8080 port, and I want to make a socket that listener on the 9090 port. When the client use the Browse visit my web on 9090 port , this socket will be send this data stream from 9090 port to 8080 port and then the Tomcat Web Server process this data and return the result to client use the 9090 port .
    =============================
    (In order to let this program suit for every model (include c/s and b/s),so I think it must be use the byte[] stream )
    ====================================================
    BinaryPort.java
    package sailing;
    import java.io.*;
    import java.net.*;
    public class BinaryPort implements Runnable
    private ServerSocket listenerSocket;
    private Socket serverSocket;
    private Socket tomcatSocket;
    private Thread myThread;
    private DataInputStream in;
    private DataOutputStream out;
    private ByteArrayOutputStream swapStream;
    public BinaryPort()
    try
    System.out.println("Server is starting ..................");
    this.listenerSocket=new ServerSocket(9090);
    this.tomcatSocket=new Socket("127.0.0.1",8080);
    this.swapStream=new ByteArrayOutputStream();
    this.myThread=new Thread(this);
    this.myThread.start();
    catch(Exception e)
    System.out.println(e);
    public void run()
    while(true)
    try
    this.serverSocket=this.listenerSocket.accept();
    this.in=new DataInputStream(this.serverSocket.getInputStream());
    byte[] buf=new byte[100];
    int rc=0;
    while((rc=in.read(buf,0,buf.length))>0)
    this.swapStream.write(buf,0,rc);
    this.swapStream.flush();
    byte[] resBuf=swapStream.toByteArray();
    this.out=new DataOutputStream(this.tomcatSocket.getOutputStream());
    this.out.write(resBuf,0,resBuf.length);
    this.out.flush();
    //Get The Tomcat Web Server reBack Information
    this.in=new DataInputStream(this.tomcatSocket.getInputStream());
    byte[] buf2=new byte[100];
    int rc2=0;
    this.swapStream=null;
    while((rc2=in.read(buf2,0,buf2.length))>0)
    this.swapStream.write(buf2,0,rc2);
    this.swapStream.flush();
    rc2=0;
    byte[] resBuf2=swapStream.toByteArray();
    this.out=new DataOutputStream(this.serverSocket.getOutputStream());
    this.out.write(resBuf2,0,resBuf2.length);
    this.out.flush();
    this.myThread.sleep(1000);
    this.out.close();
    this.in.close();
    catch(Exception e)
    System.out.println(e);
    public static void main(String args[])
    new BinaryPort();
    ====================================================
    I found that it stop on the first "while" , and I don't know what is the reason .............

    Well , I've got it ~~~~~~~~~
    if the read method hasn't the another data , this method will be stoped . so ..............
    ===============================
    package sailing;
    import java.io.*;
    import java.net.*;
    public class ModifyBinaryPort
         private ServerSocket listenerSocket;
         private Socket serverSocket;
         public ModifyBinaryPort()
              try
                   System.out.println("Server is starting ..................");
                   this.listenerSocket=new ServerSocket(9633);
                   while(true)
                        try
                             this.serverSocket=this.listenerSocket.accept();
                             new MyThread(serverSocket).start();                    
                        catch(Exception e)
                             System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
         public static void main(String args[])
              new ModifyBinaryPort();
         class MyThread extends Thread
              private Socket threadSocket;
              private Socket tomcatSocket;
              private Thread myThread;
              private DataInputStream in;
              private DataOutputStream out;
              public MyThread(Socket socket)
                   try
                        threadSocket=socket;
                        this.tomcatSocket=new Socket("127.0.0.1",9090);
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        //Read Thread
                        new ReadClientWriteTomcatThread(threadSocket,tomcatSocket).start();                    
                   catch(Exception e)
                             System.out.println(e);
         class ReadClientWriteTomcatThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              private Socket threadSocket;
              private Socket tomcatSocket;
              public ReadClientWriteTomcatThread(Socket threadSocketT,Socket tomcatSocketT)
                   try
                        threadSocket=threadSocketT;
                        tomcatSocket=tomcatSocketT;
                        read=new DataInputStream(threadSocket.getInputStream());
                        write=new DataOutputStream(tomcatSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf=new byte[100];
                        int rc=0;
                        while((rc=read.read(buf,0,buf.length))>0)
                             this.swapStream.write(buf,0,rc);
                             this.swapStream.flush();
                             if(rc<buf.length)
                                  break;
                             //System.out.println(rc);
                        byte[] resBuf=swapStream.toByteArray();
                        this.write.write(resBuf,0,resBuf.length);
                        this.write.flush();
                        //Reading the result from tomcat
                        new ReadTomcatWriteClientThread(threadSocket,tomcatSocket).start();
                   catch(Exception e)
                        System.out.println(e);
         class ReadTomcatWriteClientThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              public ReadTomcatWriteClientThread(Socket threadSocket,Socket tomcatSocket)
                   try
                        read=new DataInputStream(tomcatSocket.getInputStream());
                        write=new DataOutputStream(threadSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf2=new byte[100];
                        int rc2=0;
                        while((rc2=read.read(buf2,0,buf2.length))>0)
                             this.swapStream.write(buf2,0,rc2);
                             this.swapStream.flush();
                             if(rc2<buf2.length)
                                  break;
                        byte[] resBuf2=swapStream.toByteArray();
                        this.write=new DataOutputStream(write);
                        this.write.write(resBuf2,0,resBuf2.length);
                        this.write.flush();          
                        this.write.close();
                        this.read.close();
                   catch(Exception e)
                        System.out.println(e);
    }==================
    but it still has some little bug , I think I will work out soon .........
    Thanks for your help ejp .............

  • What's wrong with this program that about socket

    package example;
    import java.net.*;
    import java.io.*;
    public class Server implements Runnable{
        Thread t;
        ServerSocket sSocket;
        int sPort=6633;
        public Server(){
            try{
                sSocket=new ServerSocket(sPort);
                System.out.println("server start....");
            }catch(IOException e){
                e.printStackTrace();
            t=new Thread(this);
            t.start();
        public void run(){
            try{
                while(true){
                    Socket cSocket=sSocket.accept();
                    ClientThread cThread=new ClientThread(cSocket);
                    cThread.start();
            }catch(IOException e){
                e.printStackTrace();
       public static void main(String[] args){
            new Server();
    package example;
    import java.net.*;
    import java.io.*;
    public class ClientThread extends Thread{
        Socket cSocket;
        PrintStream writer;
        BufferedReader reader;
        public ClientThread(Socket s){
            cSocket=s;
            try{
                writer=new PrintStream(cSocket.getOutputStream());
                reader=new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
            }catch(IOException e){
                e.printStackTrace();
        public void run(){
            try{
                while(true){
                    String message=reader.readLine();
                    System.out.println("Server get:"+message);
            }catch(IOException e){
                e.printStackTrace();
    package example;
    import java.net.*;
    import java.io.*;
    public class Client{
        public static void main(String[] args){
            String ipaddr="localhost";
            PrintStream writer;
            try{
                Socket  cSocket=new Socket(ipaddr,6633);
                System.out.println(cSocket);
                writer=new PrintStream(cSocket.getOutputStream());
                System.out.println("client send:hello");
                writer.print("hello");
            catch(Exception e){
                e.printStackTrace();
    }first,I run Server,and then I run Client,
    output at Server:
    server start....
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.net.SocketInputStream.read(SocketInputStream.java:90)
    at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:285)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at example.ClientThread.run(ClientThread.java:20)
    what' wrong??????

    In your Client class, after doing writer.print("hello"); you should flush
    the output stream. As it is now, you attempt to write something (without actually
    sending something to your server) and main simply terminates. The server,
    still waiting for some input (you didn't flush on the client side), is confronted with
    a closed client socket (main on the client side terminated and implicitly closed
    the client socket), hence the 'connection reset' exception on the server side.
    kind regards,
    Jos

  • Two foundation questions about socket

    1
    when I close socket(this Program is still running),I open this socket again,
    why a exception happened?
    this exception is :java.net.SocketException: socket closed
    2
    when I close socket,
    I write:
    write.close();
    read.close();
    cSocket.close();
    this sequence is right?

    1
    when I close socket(this Program is still running),I
    open this socket again,
    why a exception happened?
    this exception is :java.net.SocketException: socket closedIt's in the documentation
    Socket.close()
    2
    when I close socket,
    I write:
    write.close();
    read.close();
    cSocket.close();
    this sequence is right?Harmless, but not necessary.
    The InputStream and OutputStream objects you get from Socket are just java internal constructs that use the socket filehandle. Not explicitly closing them does not cause a filehandle leak or anything like that. If you are paranoid you can doif (!Csocket.isClosed()) write.flush();
    write = null;
    read = null;
    if (!cSocket.isClosed()) cSocket.close();
    cSocket = null;

  • Simple question about sockets and streams - please answer it!

    Hi
    I have a server socket and a client socket. Both are up and runing. But I'm having problems to send a string from the client and read only the four first bytes on the server. Please read the code and some other comments below:
    socket client:
    DataOutputStream out =
    new DataOutputStream(socket.getOutputStream());
    // read from keyboard input
    BufferedReader myinput =
    new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Type any 4 chars and [enter].");
    String any = myinput.readLine();
    out.writeBytes(any);
    out.flush();
    server socket:
    in = new DataInputStream(socket.getInputStream());
    byte[] id = new byte[4];
    in.read(id, 0, 4);
    System.out.print(new String(id));
    According to the code, it should read 4 bytes from the input stream (in.read(id, 0, 4)), but it displays only the first byte. For example, if I type "hello" on client, the serve should show "hell" but it shows just "h"
    Any ideias? Thanks!

    Hi,
    Check the Javadoc for 'in.read(id, 0, 4);' This reads up to 4 bytes and returns the number of bytes read. You need something along the lines of
    int count = 0;
    while (count < 4)
    count += in.read(id, count, 4-count);
    Roger

  • About Socket program in ABAP

    Hi all,
    Can I do Socket program in ABAP?
    I know nothing about that,Can anyone help?
    Thanks very much.
    Pole

    Within ABAP you have access to OLE objects - take a look at ABAB stement SET PROPERTY.
    In our production we have some scale weights connected to a PC. On the PC an external vendor has created an OLE obejct that can retur te current state and weight of the scale weight directly into a SAP screen.
    I guess if you can write an OLE obejct that can handle it - it is possible.

  • Help! question about socket

    I set up a client socket (port 80) connected to the webserver which is using apache 1.3.14. Then I used the following code:
    Writer out=new OutputStreamWriter(connection.getOutputStream());
    out.write("GET /head.html");out.write("\r\n");
    out.flush();
    InputStream raw=connection.getInputStream();
    BufferedInputStream buffer=new BufferedInputStream(raw);
    InputStreamReader in=new InputStreamReader(buffer);
    int c;
    while((c=in.read())!=-1) {System.out.write(c);}
    It is OK until now. But when the client finished receiving the file, the socket seemed to be closed automatically. I do not know what happened to that. Please tell me how to make the socket available and usable after that? Thanks.

    I think I get it. Use this code:
    Writer out=new OutputStreamWriter(connection.getOutputStream());
    out.write("GET /menu.html HTTP/1.1");out.write("\r\n");
    out.write("Host:"+hostname);out.write("\r\n\r\n");
    out.write("GET /head.html HTTP/1.1");out.write("\r\n");
    out.write("Host:"+hostname);out.write("\r\n\r\n");
    out.flush();
    InputStream raw=connection.getInputStream();
    BufferedInputStream buffer=new BufferedInputStream(raw);
    InputStreamReader in=new InputStreamReader(buffer);
    int c;
    while((c=in.read())!=-1) {System.out.write(c);}
    Thank you so much!

  • About socket and port problem

    hi,all.
    i write a chat server use java socket. now is more than 2000 users connect to my server. but too many user make the chat message speed slow. now my server is open one port to listen the client connection. who can tell me if i change my server to open multi port to listen the client connection will rather than open one port. or it is same effect.
    please give me some advice. thanks.

    Maybe your machine is not strong enough to serve that many users at a time anyway. In that case using several ports won't help.

  • About socket thread

    May I open two sockets with different listening port numbers in a single server? For each socket, the way to deal with the inputstream and outputstream is different. May the thread be like this:
    public class twoSocketServer implements Runnable {
    public twoSocketServer() {
    try{
    SSLServerSocketFactory fact = SSLServerSocketFactory.getInstance(rand, selfPrivateKey, selfCertificate, trustEngine, null);
    serverSocket1 = (SSLServerSocket) fact.createServerSocket(ListeningPort1);
    serverSocket1.setNeedClientAuth(false);
    serverSocket2 = (SSLServerSocket) fact.createServerSocket(ListeningPort2);
    serverSocket2.setNeedClientAuth(false);
    } catch {...}
    public void run()
    while(true)
    try
    SSLSocket socket1 = (SSLSocket) serverSocket1.accept();
    new handler1(socket1).start();
    SSLSocket socket2 = (SSLSocket) serverSocket2.accept();
    new handler2(socket2).start();
    } catch {...}
    class handler1 extends Thread {...}
    class handler2 extends Thread {...}
    Is there something wrong with this idea? If yes, how can I correct it? Thanks.

    In fact you need to have independent Thread to treat each new
    incoming connection from each "server port"... instead of use it
    public void run() {
    while(true) {
    try {
    SSLSocket socket1 = (SSLSocket) serverSocket1.accept();
    new handler1(socket1).start();
    SSLSocket socket2 = (SSLSocket) serverSocket2.accept();
    new handler2(socket2).start();
    } catch {...}
    you must split it, putting each socket instance in its own thead class
    to avoid wast of time. For instance:
    class twoSocketServer {
    public twoSocketServer () {
    Thread s1 = new Thread(Server1);
    Thread s2 = new Thread(Server2);
    s1.start();
    s2.start();
    public class Server1 implements Runnable {
    public void run() {
    while(true) {
    try {
    // waitting for some Server1 client
    SSLSocket socket1 = (SSLSocket)
    serverSocket1.accept();
    new handler1(socket1).start();
    } catch(Exception ex) { }
    public class Server2 implements Runnable {
    public void run() {
    while(true) {
    try {
    // waitting for some Server2 client
    SSLSocket socket2 = (SSLSocket)
    serverSocket2.accept();
    new handler2(socket2).start();
    } catch(Exception ex) { }
    Thus each "server" will treat their clients on independent way. In
    your code your main server need to wait some server1 client to connect
    on before clients from server2.
    crt

  • Not sure about socket

    Hi folks,
    Sorry for my english, i try to expose my questions much better i can:
    I've developed an application, serverside under linux and clientside under windows.
    One time a day, linux calls (with pppd daemons and 56K ext modem) windows.
    When windows answers, the application linux side, begins, with RMI, to simulate a ftp session.
    So windows opens a file (eg: c:\test\prood.exe) and begins to transfer it to linux. In linux there's a loop that terminates only when the lenght of bytes to read from sockets is equals to 0!
    I expect to find the file written in a folder (in my case is /mnt/pool_recovery/recovery/dateoftransfer/timeoftransfer/codeofuser/proof.exe) but the lenght of file
    is 0 byte.
    I print out the content of buffer read from socket and it's ok!
    I try to execute a system operation like a copy or a move in that directory, and it's ok!
    The methods of fileoutputstream class don't generate any exception!
    If I change directory, eg /dateoftransfer/timeoftransfer/codeofuser/proof.exe i see the file written normaly!
    The JRE is 1.4 and i don't know where to watch to solve this problem.
    Can anyone help me?
    Thanks all for help!!!!

    This sounds you are relying on
    Socket.getInputStream().available() to tell you when
    the file has been completely read. It doesn't do this,
    it tells you how much data is presently buffered & can
    be read without blocking. You need to read to EOF and
    have the sender close the socket or shutdown its
    output when it has sent the whole file, or have an EOF
    application protocol.I don't use that method... I create a datainputstream from socket.getInputStream().
    Then I use dataInputStream.readByte() to write with filePutputStream.Write()...
    Thanks in advance...

  • Sorry quick question about socket apps?

    Does anyone know if there is any sort of device you can use via iphone app to work electrical sockets when you are not home, ie u plug the socket into some sort of adapter like those timer ones but that you can work via your phone? Just thinking if stuck at work etc can put lights on etc, I can't seem to find it so I'm guessing it doesn't exist? Thanks

    Hi,
    If you are searching for an iPhone app, post in the iPhone forum here.
    http://discussions.apple.com/category.jspa?categoryID=201
    Also, launch iTunes. Select iTunes Store on the left then select *App Store* in the menu then select iPhone.
    Try searching there. This is the Mac App Store forum for the Mac OS X.
    Carolyn

  • Few questions about sockets

    I'm trying to make a multiclient/server program. Few problems i stumbled upon.
    1. sending objects, i found that i have to serialize the object and send it.... but it never makes it :-/
    2. is it possible for the client to send/recieve data from the server, by giving the server the data without it requesting it, and by just asking for the data?
    Any tips would help also.

    i get this error when recieving the first time, then i get StremCorrupted exception
    SerializedObject; local class incompatible: stream classdesc serialVersionUID = 8650117693401840898, local class serialVersionUID = 839751141149923839
    Ya, i flushed the output.
    as for number 2...
    I think it was kinda answered, not sure. This server is going to be for a small "game" and i want the clients to send their data to the server, so the server can combine all of the clients data into 1 big array, that i can then send to the client when it is requested.
    I dont want the client to get data from 1 or 2 processes ago, thats why i want it to request for it when its ready, and not get it when its not needed. Because wouldn't that de-sync the clients?
    i hope that makes sense...

  • Uragent Help:about socket

    Help:
    Please tell me how client from behind firewall server can access other client from behind firewall server.

    I think you need to have dedicated port opened!! Default port is 80, which is for http. If you want to have other ports open, talk to IT!
    Hope this helps!

  • IsClosed() and isConnected() in socket ?

    //SocketTest.java
    //============
    import java.net.*;
    public class SocketTest {
        public static void main(String [] args) {
            try {
                ServerSocket ssocket = new ServerSocket(5000);
                System.out.println("Socket listening on port 5000...");
                Socket socket = ssocket.accept();
                System.out.println("Socket accepted...");
                while (socket.isConnected() && !socket.isClosed()) {
                    socket.read();
                System.out.println("Socket disconnected...");
                socket.close();
                ssocket.close();
            } catch (Exception ex) {
                System.out.println(ex);
    //ClientTest.java
    //============
    import java.net.*;
    public class ClientTest {
        public static void main(String [] args) {
            try {
                Socket socket = new Socket("127.0.0.1", 5000);
                System.out.println("Connected...");
                socket.close();
                System.out.println("Disconnected...");
            } catch (Exception ex) {
                System.out.println(ex);
    }Consider the example at above... It's seem that server wouldn't know the client was closed/disconnected unless the server tried to write something to it outputstream. So, how can i know if my client socket is closed or disconnect ? What is the usage of isConnected() and isClosed() ?

    Sorry... 1 more question here...
    So, I can't check whether a socket was disconnected
    unless checking of it inputstream or outputstream ?The method Socket#isConnected() returns true if the socket successfuly connected to a server. With that in mind, check out the following:
    http://java.sun.com/docs/books/tutorial/networking/sockets/definition.html
    Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
    On the client-side: The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. To make a connection request, the client tries to rendezvous with the server on the server's machine and port.
    If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.
    On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. Note that the socket on the client side is not bound to the port number used to rendezvous with the server. Rather, the client is assigned a port number local to the machine on which the client is running.
    The client and server can now communicate by writing to or reading from their sockets.
    Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

Maybe you are looking for