How to control tcp connection with java tcp socket programing ??

Hi,
I am connecting a server as using java socket programming.
When server close the connection (socket object) as using close() method ,
I can not detect this and My program continue sending data as if there is a connection with server.
How to catch the closing connection ( socket ) with java socket programming.
My Client program is as following :
import java.io.PrintWriter;
import java.net.Socket;
public class client
  public client()
   * @param args
  public static void main(String[] args)
    Socket socket=null;
    PrintWriter pw=null;
    try
                      socket = new Socket("localhost",5555);
                      pw = new PrintWriter(socket.getOutputStream(),true);
                      int i=0;
                      while (true)
                        i++;
                        pw.println(i+". message is being send.");
                        Thread.sleep(5000);
    } catch (Exception ex)
                      ex.printStackTrace();
    } finally
                      try
                        if(pw!=null)pw.close();
                        if(socket!=null)socket.close();
                      } catch (Exception ex)
                        ex.printStackTrace();
                      } finally
}

I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class client
  public client()
   * @param args
  public static void main(String[] args)
    Socket socket=null;
    PrintWriter pw=null;
    BufferedReader bufIn=null;
    InputStreamReader inRead=null;
    InputStream in=null;
    try
                      socket = new Socket("localhost",5555);
                      in = socket.getInputStream();
                      inRead = new InputStreamReader(in);
                      bufIn = new BufferedReader(inRead);
                      pw = new PrintWriter(socket.getOutputStream(),true);
                      int i=0;
                      while (true)
                        i++;
                        try
                          bufIn.readLine();
                          pw.println(i+". message is being send.");
                          System.out.println(i+". message has been send");
                        } catch (Exception ex2)
                          System.out.println(ex2.toString());
                          System.out.println(i+". message could not be send");
                        } finally
                        Thread.sleep(5000);
    } catch (EOFException ex)
                      ex.printStackTrace();
    } catch (InterruptedException ex)
                      ex.printStackTrace();
    } catch (IOException ex)
                      ex.printStackTrace();
    } finally
                      try
                        if(pw!=null)pw.close();
                        if(socket!=null)socket.close();
                      } catch (Exception ex)
                        ex.printStackTrace();
                      } finally
}

Similar Messages

  • Need help with java.nio.socket program.

    Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
    SocketIn.java:48: incompatible types
    found : java.nio.channels.SocketChannel
    required: java.net.Socket
    Socket requestSocket = requestChannel.accept();
    Here is my code:
    package NETC;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    public class SocketIn{
         // Buffer for any incoming data.
         private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
         CharBuffer charBuffer = null;
         public SocketIn(int intPort)throws Exception{
              // Create a non-blocking server socket.
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // Use the host and port to bind the server socket.
              InetAddress inetAddress = InetAddress.getLocalHost();
              InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
              serverChannel.socket().bind(socketAddress);
              // The selector for incoming requests.
              Selector requestSelector = SelectorProvider.provider().openSelector();
              // Put the server socket on the selectors 'ready list'.
              serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
              while(requestSelector.select() > 0){
                   System.out.println("Connection Accepted...");
                   // A request has been made and is ready for IO.
                   Set requestKeys = requestSelector.selectedKeys();
                   Iterator iterator = requestKeys.iterator();
                   while(iterator.hasNext()){
                        SelectionKey requestKey = (SelectionKey)iterator.next();
                        // Get the socket that's ready for IO.
                        ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
                        // This shouldn't block.
                        Socket requestSocket = requestChannel.accept();
                        inBuffer.clear();
                        requestSocket.read(inBuffer);                    
                        inBuffer.flip();
                        Charset charset = Charset.forName("ISO-8859-1");
                        CharsetDecoder decoder = charset.newDecoder();
                        charBuffer = decoder.decode(inBuffer);
                        iterator.remove();                    
    }

    Well its been about a month and a half so I guess you have your answer. In case you don't...
    // This shouldn't block.
    Socket requestSocket = requestChannel.accept();
    The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
    You can get access to the socket using the SocketChannel.
    SocketChannel requestSocketChannel = requestChannel.accept();
    Socket requestSocket = requestSocketChannel.socket();
    But you don't need the socket to read and write.

  • About: control USB device with Java

    Any body know how to control USB device with Java?
    Does JDK provide a package for USB?
    Is there any web site concerning USB programming?
    Thank you! ^_^

    Look at www.prosyst.com. There is an usb bundle (linux
    and windows pltforms).I looked on this site and cannot find the bundle you are talking about. Do you know more specifically where to find out about controlling USB devices with Java?

  • Creating a TCP connection with SSL/TLS

    Hi,
    I am working in a application that depends on the server. I need to estabilish a TCP connection with SSL/Tls secure connection with the server in order to get the datas.
    I have the following code structure :
    - (id)initWithHostAddressNSString*)_host andPortint)_port
    [self clean];
    self.host = _host;
    self.port = _port;
    CFWriteStreamRef writeStream;
    CFReadStreamRef readStream;
    return self;
    -(BOOL)connect
    if ( self.host != nil )
    // Bind read/write streams to a new socket
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDef ault, (CFStringRef)self.host, self.port, &readStream, &writeStream);
    return [self setupSocketStreams];
    - (BOOL)setupSocketStreams
    // Make sure streams were created correctly
    if ( readStream == nil || writeStream == nil )
    [self close];
    return NO;
    // Create buffers ---- has not been released , so need to check possible ways to release in future
    incomingDataBuffer = [[NSMutableData alloc] init];
    outgoingDataBuffer = [[NSMutableData alloc] init];
    // Indicate that we want socket to be closed whenever streams are closed
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    //Indicate that the connection needs to be done in secure manner
    CFReadStreamSetProperty(readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
    // We will be handling the following stream events
    CFOptionFlags registeredEvents = kCFStreamEventOpenCompleted |
    kCFStreamEventHasBytesAvailable | kCFStreamEventCanAcceptBytes |
    kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
    // Setup stream context - reference to 'self' will be passed to stream event handling callbacks
    CFStreamClientContext ctx = {0, self, NULL, NULL, NULL};
    // Specify callbacks that will be handling stream events
    BOOL doSupportAsync = CFReadStreamSetClient(readStream, registeredEvents, readStreamEventHandler, &ctx);
    BOOL doSupportAsync1 = CFWriteStreamSetClient(writeStream, registeredEvents, writeStreamEventHandler, &ctx);
    NSLog(@"does supported in Asynchrnous format? : %d :%d", doSupportAsync, doSupportAsync1);
    // Schedule streams with current run loop
    CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    // Open both streams
    if ( ! CFReadStreamOpen(readStream) || ! CFWriteStreamOpen(writeStream))
    // close the connection
    return NO;
    return YES;
    // call back method for reading
    void readStreamEventHandler(CFReadStreamRef stream,CFStreamEventType eventType, void *info)
    Connection* connection = (Connection*)info;
    [connection readStreamHandleEvent:eventType];
    // call back method for writing
    void writeStreamEventHandler(CFWriteStreamRef stream, CFStreamEventType eventType, void *info)
    Connection* connection = (Connection*)info;
    [connection writeStreamHandleEvent:eventType];
    `
    As above, I have used
    CFReadStreamSetProperty(readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3);
    in order to make a secured connection using sockets.
    The url i am using is in the format "ssl://some domain.com"
    But in my call back method i am always getting only kCFStreamEventErrorOccurred for CFStreamEventType .
    I also tried with the url "https://some domain.com" ,but getting the same error.
    i also commented out setting kCFStreamPropertySocketSecurityLevel, but still i am receiving the same error that i mentioned above.
    I dont know how it returns the same error. I have followed the api's and docs , but they mentioned the same way of creating a connection as i had given above.
    I tried to get the error using the following code :
    CFStreamError error = CFWriteStreamGetError(writeStream);
    CFStreamErrorDomain errDomain = error.domain;
    SInt32 errCode = error.error;
    The value for errCode is 61 and errDomain is kCFStreamErrorDomainPOSIX. so i checked out the "errno.h", it specifies errCode as "Connection refused"
    I need a help to fix this issue.
    If the above code is not the right one,
    **(i)how to create a TCP connection with SSL/TLS with the server.**
    **(ii)How the url format should be(i.e its "ssl://" or "https://").**
    **(iii)If my above code is correct where lies the error.**
    I hope the server is working properly. Because I can able to communicate with the server and get the datas properly using BlackBerry and android phones. They have used SecuredConnection api's built in java. Their url format is "ssl://" and also using the same port number that i have used in my code.
    Any help would be greatly appreciated.
    Regards,
    Mohammed Sadiq.

    Hello Naxito. Welcome to the Apple Discussions!
    Try the following ...
    Perform a "factory default" reset of the AX
    o (ref: http://docs.info.apple.com/article.html?artnum=108044)
    Setup the AX
    Connect to the AX's wireless network, and then, using the AirPort Admin Utility, try these settings:
    AirPort tab
    o Base Station Name: <whatever you wish or use the default>
    o AirPort Network Name: <whatever you wish or use the default>
    o Create a closed network (unchecked)
    o Wireless Security: Not enabled
    o Channel: Automatic
    o Mode: 802.11b/g Compatible
    Internet tab
    o Connect Using: Ethernet
    o Configure: Manually
    o IP address: <Enter your college-provided IP address>
    o Subnet mask: <Enter your college-provided subnet mask IP address>
    o Router address: <Enter your college-provided router IP address>
    o DNS servers: <Enter your college-provided DNS server(s)
    o WAN Ethernet Port: Automatic
    <b>Network tab
    o Distribute IP addresses (checked)
    o Share a single IP address (using DHCP & NAT) (enabled)

  • SbRIO-9612 unable to close a TCP connection without causing TCP failure

    Hello,
    I'm working on a multi-server (sbRIO-9612's), multi-client (Windows PCs) application which uses the STM 2.0 libraries and LV2009 SP1.  The server listens on a UDP port for the client to send a message - once sent, the server opens the TCP connection to the client and all is well . . .
    . . . until I added a "hearbeat" message to monitor for down connections.  Once the TCP connection has been extablished, the client PC sends a TCP message (a request for the number of clients connected) to the server sbRIO-9612 every 5 seconds - both the client and server are coded to close the connection if a message is not received within 10 seconds.  The client-side app works fine - if the TCP message is not returned in 10 seconds, the connection is closed and a new UDP message is sent to re-establish it.
    The server-side is the problem - if no message is received in 10 seconds, the TCP connection is closed o.k. (no errors), but the server will no longer allow new TCP connections to be established unless it's rebooted.  It seems to work fine if I leave the non-communicating TCP connections open on the server-side, but I can see this leading to problems after several clients have disconnected without notifying the server properly.
    Interestingly, if the client closes the TCP connection properly (via TCP Close in LV), the server detects it fine and there is no problem.
    I'm allowing the operating system on both sides to select the TCP port to use.
    Any help is greatly appriciated - thank you!
    Al

    Hi Al,
    Thanks for the update -- I'm glad that you were able to find that the issue wasn't actually with the TCP VIs, and moreover that LabVIEW 2010 SP1 seems to have resolved the issue. I would still recommend combing through the code on the RT end to ensure that the LabVIEW 2010 SP1 upgrade really did 'fix' the underlying issue. It's somewhat strange that a version upgrade resolved TCP communication issues that you were having. I just want to be sure that the solution is a truly stable one.
    Sanjay C.
    Embedded Software Product Manager| National Instruments

  • How can i create messenger with java tv API on STB

    deal all.
    how can i create messenger with java tv API on STB.
    how can Xlets communicate each other?
    how?
    i am interested in xlet communications with java tv.
    is it impossible or not?
    help all..

    You can create a messenger-style application using JavaTV fairly easily. JavaTV supports standard java.net, and so any IP-based connection is pretty easy to do. The hard part of the application will be text input, but people have been using cellphone keypads to send SMS messages for long enough that they're familiar with doing this. This doesn't work well for long messages, where you really need a decent keyboard, but for short SMS-type messages it's acceptable.
    The biggest problem that you need to work around is the return channel. Many receivers only have a dial-up connection, ties up the phone line and potentially costs people money if they don't get free local calls. Always-on return channels (e.g. ADSL or cable modem) are still pretty uncommon, so it's something that you nee to think about. Of course, if you do have an always-on connection then this problem just goes away.
    This is really one of those cases that's technically do-able, but the infrastructure may not be there to give users a good experience.
    Steve.

  • How to change a connection with the database in Runtime?

    How to change a connection with the database in Runtime?
    My connection was made using ADF Business component (ApplicationModule).
    ADF Swing.
    JDeveloper Studio 11.1.1.4.0.

    When deploying ADF applications with database connection, you should be using JDBC data sources configured in the weblogic server.
    You could change the JDBC data sources to a different DB instance or location - by changing the JDBC data source and restarting the weblogic server.
    For more details, check
    http://techiecook.wordpress.com/2010/12/02/oracle-weblogic-adf-datasources/
    Thanks,
    Navaneeth

  • Is this how i control frame rate with IMAQdr property node?

    Is this how i control frame rate with IMAQdr property node? if not, can someone point me in the right direction? for some reason, it doesnt work..
    Attachments:
    pic.JPG ‏75 KB

    Please see this related thread http://forums.ni.com/t5/LabVIEW/IMAQdr-Property-No​de/m-p/1642950/highlight/false#M590168
    Matt
    Product Owner - NI Community
    National Instruments

  • How to resotre the connection with source sys

    hello friends ,
    need some help.
    COuld you please let me know how to retore the connection with R/3 system ?
    Unfortunately the R/3 systems are refreshed and connection has to be restore now with BW . As Here i do not have basis person in team , could you please let me know how to do this ?
    Thanks in advance
    Regards
    Manoj

    hai jain,
    first of all check out the connection is exit with r/3 system. select your r/3 systemselect customizing for extractorsif the connection is available it will lead to r/3 system. it will ask  user id and password for that system. other wise select the r/3 s.s--select check.
    if you want to restoreselect the source(r/3)right click itselect restore.
    hope this help you
    regards
    harikrishna N

  • XIO: fatal IO error connection with a remote socket was reset by socket

    dear all ,
    i have ebs running on aix 6 server
    oracle db : 11.1.0.7.0 - 64bit
    ebs version : 12.1.1
    the problem is i have report running on cuncurent schedule , but the result with status complete error ,
    when i view log , it shawn error below this
    Enter Password:
    XIO: fatal IO error 73 (A connection with a remote socket was reset by that socket.) on X server "localhost:0.0"
    after 498 requests (469 known processed) with 4267 events remaining.
    Report Builder: Release 10.1.2.3.0 - Production on Mon Sep 24 20:04:26 2012
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Start of log messages from FND_FILE
    End of log messages from FND_FILE
    Program exited with status 1
    Concurrent Manager encountered an error while running Oracle*Report for your concurrent request 30072710.
    Review your concurrent request log and/or report output file for more detailed information.
    Executing request completion options...
    ------------- 1) PUBLISH -------------
    Beginning post-processing of request 30072710 on node SMJKT-PRFN02 at 25-SEP-2012 00:05:51.
    Post-processing of request 30072710 completed at 25-SEP-2012 00:05:55.
    any suggest to solve this error ?
    thanks
    Imron S
    Edited by: Imron Siagian on Sep 24, 2012 8:57 PM
    Edited by: Imron Siagian on Sep 25, 2012 2:57 AM

    Hi;
    XIO: fatal IO error 73 (A connection with a remote socket was reset by that socket.) on X server "localhost:0.0"after 498 requests (469 known processed) with 4267 events remaining
    Similar issue mention at below note.Please review:
    What Happens When an NMS User Kills Their Exceed onDemand or Exceed Session Via Windows Task Manager [ID 1072528.1]
    Regard
    Helios

  • Connect to a printer via TCP connection with wifi

    Hi,
    what i would like to do, is to connect a printer to the iPhone via wireless.
    The printer is in the same wifi as the iPhone and the ip adress is known.
    So what i started to to is, to create a SocketConnection with CFStreamCreatePairWithSocketToHost(...). But if i switch of the printer, the inputstream is created too, and is not NULL as expected.
    Is this the right approach im using or is there a better possibilty to send strings to my printer using a tcp connection over wifi?
    Regards,
    Grinarn

    Welcome to Apple Discussions!
    In the Help menu of the Finder is a little app called Mac Help. Most Apple apps and many 3rd party apps also use Mac Help. In Mac Help is an article called *Adding a printer shared by a Windows computer via SMB/CIFS*. This article is regarding sharing a printer that is connected to a PC over a network however, and not to a router, but may have info useful to troubleshooting. You might also check with your Linksys user guide for info on sharing this printer with a Mac over the network.

  • Max. no. of Socket (TCP) Connection in Java

    Dear All,
    Made a java based chat program for a business application. Having serious problem, when the number of users exceeds 28 all the client sockets connected to the server throws java.io.EOFException.
    Tested the server in couple of machines, when the socket connections touches 29 its not responding. Is there any limitation or setup to be done to use maximum no. of socket connection in JVM or in Operating System ?
    Please help me out. Its really very very urgent
    Server running in a PC machine loaded with Windows 2003 Server
    Rgds
    VenQuet
    Edited by: venquett on Apr 8, 2008 3:54 AM

    all the client sockets connected to the server throws java.io.EOFExceptionThat indicates that the server has closed them all. Are you sure that's the exception you get?
    You should be able to get hundreds of connections. The limit is not imposed by Java but by your operating system, or possibly the server.

  • How to get php content with java ??

    i have made a php file what will display a number,
    here's a example
    <?php
    if ($action == "answer"){
    echo "18274926";
    ?>
    no i want to get the number with java
    so here's my java code
    import java.io.*;
    import java.net.*;
    import java.util.Date;
    class URLConnecties
        public static void main(String args[]) throws Exception
            int teken;
            URL url = new URL("http://www.gamer.mineurwar.nl/net/javachallenge.php?command=DaTe");
            URLConnection urlconnection = url.openConnection();
            System.out.println("Type inhoud: " +
                urlconnection.getContentType());
            System.out.println("Datum document: " +
                new Date(urlconnection.getDate()));
            System.out.println("Laatst gewijzigd: " +
                new Date(urlconnection.getLastModified()));
            System.out.println("Document vervalt: " +
                urlconnection.getExpiration());
            int lengteinhoud = urlconnection.getContentLength();
            System.out.println("Lengte inhoud: " + lengteinhoud);
            if (lengteinhoud > 0) {
                InputStream in = urlconnection.getInputStream();
                while ((teken = in.read()) != -1) {
                    System.out.print((char) teken);
                in.close();
    }if you change the url ro a .html file it displays the code correctly(source),
    but when trying to get the content of a php file (the number)
    it says that there is no content from the php file
    yhe source of the original php file what's in the code can be found at
    www.gamer.mineurwar.nl/net/javachallenge.txt

    The 'content' is generated dynamically by a PHP script so the "content lenght" can't be known in advance by the server. For this reason connection.getContentLenght() returns -1; it doesn't mean that there is no content, only that it can't be known how much there will be.
    To solve the issue, remove the if statement from around the while-loop:// if (lengteinhoud > 0) { DELETE THIS LINE
    InputStream in = urlconnection.getInputStream();
    while ((teken = in.read()) != -1) {
        System.out.print((char) teken);
    // } and this too

  • Controlling eletronic devices with JAVA ( LEDS, MOTORS...)

    All this week I try to find some help about how to control eletronic devices like leds using the parallel or serial port using JAVA. Using C it's very simple, but with JAVA, I guess that NOBODY do this kind of application... If I'm wrong, please, tell me.... ( I know that I need to use javax.comm or JNI, but I want to see a real application that works ...

    First thing to note is that using javax.comm you cannot set pin outputs
    levels directly (you can set some pin levels directly such as CTS and
    RTS on a serial port). There are ways around this such as writing the correct byte value to the parallel port (depends on port type though)
    Therefore the device you wish to communicate with should be able
    to talk to parallel or serial ports. If this is the case you just send
    messages to the device and it lights up you leds.
    A, perhaps better, solution would be to write, or obtain from the
    internet, some native lib that allows bit bashing on the port of your
    choice. Then write a wrapper class for it an call its methods (JNI).
    This is only worth while if you have some reason to use java rather
    then another language, such as C or C++, to talk to you device. This
    whole thing would probably be easier in one of those languages.
    matfud

  • How to share a folder with java? in netbios in windows

    hi. I want to write a programa that user can select a directory than
    click the share button and the directory will be shared to other pcs.
    the other pcs can acces this directory like \\servername\shareddirectory
    the question is this. how can i share a director with java or JNI's?
    please help me.
    with my best regards....

    thanks about net share command.
    i know how to use Runtime.getRuntime.exec()
    but i cont find the syntax of net share command.
    can u give an example? i use net help share and i try different
    sytaxes but i cant find the correct one.
    please give an examle about net share command.
    thanks a lot.

Maybe you are looking for