Java Sockets Question

Hi Guys,
I've got a problem. I'm using raw socket connections for Web and other queries. I know I can use URLConnect and similar but they do not provide the flexiblity that I need so please do not suggest that I use those isntead.
My problem is that I can set the read timeout (socket.setSoTimeout) and I can set the write timeout (socket.setLingerTimeout) but I there does not appear to be a setting to set the connection timeout.
I'm using this for proxy servers, and the proxy servers tend to die quite often and when I try to connect to a server that no longer works the connection request just sits there forever, never actually times out. Now, the timeouts work fine on the read/write but not on the connection.
I know I can create another thread that's a timer and force close the socket thread but that doesn't seem like the proper way to do it.
Thanks,

Great. Thanks, Played with that overloaded constructor and finally got it to work under linux. The funny thing is it wouldn't work under windows when I was testing because windows uses its own timeout.

Similar Messages

  • Java Socket Question

    Bonjour all,
    I have a bit of a weird question about Socket output and input streams, when I use the following code everything works fine.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Send data request+
    +DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    How ever if I declare my Output and Input Stream readers together, my program justs hangs.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Define streams+
    DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    +//     Send data request+
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    Anyone got any ideas why this is??
    Edited by: 836869 on 15-Feb-2011 04:02

    You have to flush your ObjectOputStream first, it is worth noting that you are not, 1) using an ObjectOutputStream, 2) flushing it before opening the ObjectInputStream.
    Try this.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());If you want to swap an integer as part of the header, you can do the following.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.writeObject(INT);
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    Integer intValue = (integer) ois.readObject();

  • Java socket not handling the data packets properly

    I have created a small webserver application where i am receiving http requests from a siebel client. I am using content-length parameter to read the complete data in a buffer string using the command inputstreamreader.read. It works fine in all the cases, except when its used with a firewall. Some times the firewall splits a message into 2 and my logic fails as it doesn't find as many characters in the first packet as mentioned in the content length.
    My question is , how can i take care of these scenarios where a firewall is splitting the messages into multiple packets. why the java socket class is not handling the merging of these packets?
    any pointers are welcome.
    thanks

    Because that's the way TCP/IP works. read() gives you the data it can, and tells you how much was actually read. It's up to the application to reconstruct the application-level object. You could do something like this:    byte[] content = new byte[contentLen];
        int offset = 0;
        int remaining = contentLen;
        int currBytesRead = 0;
        while (remaining > 0 && currBytesRead != -1) {
          int currBytesRead = mySocketInputStream.read(content, offset, remaining);
          remaining -= currBytesRead;
          offset += currBytesRead;
        } (Warning: that's off the top of my head, uncompiled and untested. Use for demonstration purposes only!)
    Grant

  • Using plain Java Sockets(not RMI) how..?

    hi!
    1. Using plain Java Sockets(not RMI) how can the client detect when its server
    goes down?
    There is a long time interval between client requests and the client wants
    to retain a live connection rather than disconnect after every reqest.
    Please also cc your reply to [email protected]
    Thanks,
    \Raghu

    If you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Java socket streams messing up

    iv wrote a games server and it uses java socket streams to send the messages back and forth between the game clients and the game server it self
    this all works great but when running and over about 5min its send over 1000 packets BUT
    it will crash iv found the reason is down to when reading the packets my parser is reading wrong part and grabbing a String part when it should be a INT
    now it should NEVER be reading this part of the packet so i put a trace on the packets coming in and ran it every packet was been read in perfect THEN just befor the crash TWO packets were merged together stright out from the socket stream this is y my packet reader was getting confused
    what im asking is can this happen in java sockets ? i thought they were bufferered so no matter how fast you send data it would always read it out in the same order ?? not sure how its merging these to packets
    is this possible of is my reader got an error in it altho works 95% of the time ??

    or do you have multiple buffered streams created from the same socket?

  • Flash/java remoting question

    Hi,
    i'm new to flash remoting and am finding using it with java
    quite troublesome. I've also found using the FileReference class
    troublesome if you use java. my question is can you somehow tie the
    remoting functionality to the FileReference.upload method
    fucntionality??
    thanks in advance

    I will use the program with photo detector to test
    the response time of the LCD screenWhy Java?I second that. With a test like that, you want to reduce the experiment down to a single variable, in this case the lcd response time. Using a java program to feed the monitor input introduces a second variable, the response time of the program. The java program's timer may not be exact, the components may not be repainted completely quickly enough, etc. If this is just for your own amusement, maybe that doesn't matter, but if you want your results to have any reliability, you'll need a more accurate and controllable input source.

  • Unix Domain Socket - Question about work around

    Since Unix Domain Sockets are platform dependent and Java is platform independent, it does not support it.
    However, I am sure some of you have worked with them and found some good work around.
    Elsewhere Jtux was suggested as a possible fix. However, I have not seen any good testimonials to it working. Also, if there are any security issues with this software. The website is here: http://www.basepath.com/aup/jtux/
    Does anyone have any other suggest?
    Thanks.

    I am modifying a current app. I must use the Unix
    Domain Sockets. I have no choice in the matters. It's
    for security reasons that they must be left in place.I can only guess that you do not understand my suggestion.
    The proxy does a domain socket to regular socket - just a pass through. You write this in C/C++.
    In your java app, as one option, you use Runtime.exec() to start the proxy. Then you use a java socket to connect to it. You can pass options to the proxy to control the socket behavior on both ends.
    In terms of usage there are a number of variations on the above.

  • Socket AS3 ( Receive File .TXT ) + Java Socket

    Hi,
    I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
    Souce Java :
    public void sendFile(String fileName) {
            try {
                //handle file read
                File myFile = new File(fileName);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);
                OutputStream os = clientSocket.getOutputStream();
                byte[] fileSize = intToByte(mybytearray.length);
                byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
                System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
                System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
                DataOutputStream dos = new DataOutputStream(os);
                //dos.writeUTF(myFile.getName());
                //dos.writeInt(mybytearray.length);
                dos.write(clientData, 0, clientData.length);
                dos.flush();
    AS3 Source..
    private function onResponse(e:ProgressEvent):void {
      var file:File;
      var fs:FileStream;
      var fileData:ByteArray = new ByteArray();
      file = File.documentsDirectory.resolvePath("tmpReceive.txt");
      fs = new FileStream();
      fs.addEventListener(Event.CLOSE,onCloseFileReceive);
    if(_socket.bytesAvailable > 0) {
      while(_socket.bytesAvailable) {
      // read the socket data into the fileData
      _socket.readBytes(fileData,0,0);
      fs.open(file, FileMode.WRITE);
      // Writing the file
      fs.writeBytes(fileData);
      fs.close();

    Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
    issue a close() call. So if you are going to do
    crypto, you will need to trap the close() before it
    reaches the underlying socket streams. This is
    because the close() method finalizes the cryptographic
    operation. (Flush() would make more sense, no idea
    why they did it this way). You do want to finalize
    the crypto for any given message, but you need to trap
    the close() before it hits the socket and ends the
    whole affair.
    I don't see anything about that in the bug database.
    No matter what streams you are using, if you aregoing to keep the socket open for multiple
    request-response round-trips, you need to very closely
    pay attention to how much data is being sent on each
    trip. Normally, you can fudge this a bit on a
    request-response because the close() call on the
    output stream will cause the receiving input stream to
    behave more or less properly. However, a flush() will
    not.Why not? I use that all the time with no problem.
    A good practice is to send the content-length of
    the message first, so the receiving input stream
    "knows" when to stop reading, does not block, and then
    can send its own bytes back the other direction.
    (Where the process is repeated).
    An alternative is to use two threads: read and write.
    The read recieves, parses, validates and then pushes complete messages to a queue.
    The write pulls messages from the queue, processes and send a result.
    A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

  • JAVA SOCKET TIMEOUT WHEN GENERATING PDF TO ADS SERVER

    We are currently getting the error when attempting to generate the PDF from the thin portal BI Reports and recieved the JAVA SOCKET READ TIME OUT error and
    applied adjustments to the notes
    934725 and 826419 by changing the timeout sessions to 300, but still get the same timeout errors:
    Note: We changed ADUSER user type and password, passed rpcData test, RFC HTTP external connections to ADS server...so we've came a long ways and here we are now with the timeout errors...
    Any ideals???

    Hi
    when you reset password please select checkbox for password never expires.
    see the following notes :
    1.Note 944221 - Troubleshooting if problems occur in forms processing
    2.Note 811342 - Time Out exception when rendering to Adobe document service
    thanks
    Gopal

  • The service bit "write enable" in Java Socket

    Hello,
    I am trying to communicate with a third party application and I am having some problems. I use a standard Socket connection, were my application is the Server (ServerSocket). The connection is established, but no data is transmitted.
    I talked with the guys behind this third party application, and they said that perhaps their application does not receive a "write enable" service bit of the tcp/ip protocol. I'm not a network wiz, so this is an unknown territory for me.
    So I ask you. What is this "write enable" tcp/ip service bit? Is this per default on in java socket connections? If no, how can I change this?
    Perhaps this is very basic knowledge, but I've googled a bit and have not found this "service bit".

    This could refer to something in their
    protocol which you aren't implementing correctly.Probably, but I believe they have "forgotten" to mention that it is required in our implementation.
    OTOH if you are the server the transaction would
    normally begin with a request from the client, not a
    write-enablement from the server.The defined protocol smelled fishy when reading the "whitepaper", but we had to accept it (politics).

  • Java sockets (peek functionality)

    Hi,
    how do i peek at a datagram, look into the data and accordingly
    decide whether to consume that datagram or leave it for later
    processing?
    Is this something Java sockets readily support OR do I need
    to implement some kind of store-for-later-processing
    please help
    Thanks.

    java.net.DatagramSocket doesn't have peek support in the API at this time - see 4102648.
    If you were to use a non-blocking DatagramChannel and register it with a Selector then you should be notification that a packet can be read. Okay, it doesn't give you the details - just that a packet is available but it may help in your environment.

  • Java sockets forwarding (redirect)

    Dear all
    I’m try to write a java sockets program which will accept VNC connection and forward it to another pc that has VNC server installed.
    That is: a client use vnc viewer connect to a JavaServer(where the sockets program run), the JavaServer accept this connection and forward it to the VNC server
    The reason doing this is because the client can only connect to the JavaServer, and the JavaServer has the ability to connect any host.
    I can manage to initiate the connection, and give the password that the VNC server request with the following code, but after this just before the viewer start to show the remote desktop, the sockets stuck on reading.
    can anyone help me out please.
    public void listen() throws Exception
    ServerSocket server=new ServerSocket(443, 5);
    System.out.println("Start Listen ...");
    while(true)
    Socket serverCon=server.accept();
    System.out.println("get Connection from: "+serverCon.getInetAddress());
    InputStream serverIn=serverCon.getInputStream();
    OutputStream serverOut=serverCon.getOutputStream();
    Socket targetCon=new Socket("192.168.1.3", 5900);
    InputStream targetIn=targetCon.getInputStream();
    OutputStream targetOut=targetCon.getOutputStream();
    byte[] buf=new byte[10240];
    int len;
    while(true)
    len=targetIn.read(buf);
    System.out.println(len);
    serverOut.write(buf, 0, len);
    len=serverIn.read(buf);
    System.out.println(len);
    targetOut.write(buf, 0, len);
    }

    Hi EJP
    Thanks for your reply,
    I did try to use threads with pipeStream,
    but it’s worse than the simple one,
    since it cannot even initiate connect between two side,
    the following is the sample code I use, which I leaned from here http://home.tiscali.nl/bmc88/java/sbook/029.html
    I can't found any more info regard to this topic on the internet, can you give me a hint.
    thanks a lot.
    public void listen2() throws Exception
      ServerSocket server=new ServerSocket(443, 5);
      System.out.println("Start Listen ...");
      while(true)
       Socket serverCon=server.accept();
       System.out.println("get Connection from: "+serverCon.getInetAddress());
       InputStream serverIn=serverCon.getInputStream();
       OutputStream serverOut=serverCon.getOutputStream();
       Socket targetCon=new Socket("192.168.1.1", 5900);
       InputStream targetIn=targetCon.getInputStream();
       OutputStream targetOut=targetCon.getOutputStream();
       PipedInputStream serverPin=new PipedInputStream();
       PipedOutputStream serverPout=new PipedOutputStream(serverPin);
       PipedInputStream targetPin=new PipedInputStream();
       PipedOutputStream targetPout=new PipedOutputStream(targetPin);
       while(true)
        ReadThread rt=new ReadThread("reader", targetIn, serverPout);
        ReadThread wt=new ReadThread("writer", serverPin, serverOut);
        ReadThread rt2=new ReadThread("reader", serverIn, targetPout);
        ReadThread wt2=new ReadThread("writer", targetPin, targetOut);
        rt.start();
        wt.start();
        rt2.start();
        wt2.start();
    class ReadThread extends Thread implements Runnable{
      InputStream pi=null;
      OutputStream po=null;
      String process=null;
      ReadThread(String process, InputStream pi, OutputStream po)
       this.pi=pi;
       this.po=po;
       this.process=process;
      public void run()
       byte[] buffer=new byte[1024];
       int bytes_read;
       try
        for(; ; )
         bytes_read=pi.read(buffer);
         if(bytes_read==-1)
          return;
         po.write(buffer, 0, bytes_read);
       catch(Exception e)
        e.printStackTrace();
    }

  • C# socket and java socket

    hello
    i am a java programmer,recently we got a project,that need the c# app to communicate with java app ,i select the socket as intermediate.
    i notice that java socket term is divided into " blocking" and "non-blocking",the latter come from jdk1.4, the c# socket is devided into "synchronized" and "asynchronized" and both of them are blocking,
    in my project,i have tried synchronized c# socket coorperating to blocking java socket,it works well..but when i modify the c# app to ASYNCHRONIZED socket,my system DON'T works well,i don't know why? i can't find asynchronized socket in java,.i learn that nio socket is nonblocking, is it asynchronized?
    who can tell me what's is the best solution for the socket communication between java and c#?

    yes,i have read them,but it only tell me the communication between java apps,and DON'T tell me any clue about c# socket.

  • Java Sockets - help with using objects

    I am new to java sockets, and need to come up with a way to send a user defined instance of a class across a basic client/server application.
    I can not find out how to do this. I read the tutorials, but my class can not be serialized. How can I send/recieve this instance of a user defined class?

    right off the top of my head, doesn't serialver just spit out a UID for a given set of classes?
    To mark a class as Serializable, just implement the java.io.Serializable class - then you could use the readObject/writeObject methods of the ObjectInputStream/ObjectOutputStream classes.
    Good luck
    Lee

Maybe you are looking for