Blocked socket connection

Hi all,
I have a little chat J2ME (midp2) application that connects to the server through SocketConnection at a high (>1024) port. On the emulator everything works perfectly. When running on the handsets (I used Sony Ericsson JP-5 family & Samsung Z230, Z720), I ran into 2 separate problems:
1. Operator-blocked port:
When testing on different operators' SIM cards, I found that one of them was not able to connect to the server. Monitoring the packet arrival at the server, I saw nothing at all from this mobile operator's gateway.
The Question: is there a workaround to this port-blocking problem other than scanning several port ranges? Can operators / do they normally block non-http traffic to port 80? If these methods are blocked, what other ways can connection be achieved? (What do typical chat apps--MSN/Yahoo--use?) Is there a way to "wrap around" the payload over HTTP?
2. SecurityException:
In the code section where the SocketConnection is initiated, when I put a try-catch SecurityException, one is indeed caught. When I remove this try-catch, the midlet works -- it connects fine to the server!
I saw in other forums (Sony-Ericssons') that this securityException is thrown when the midlet which is not a trusted 3rd-party application, tries to connect to a socket on ports 80, 443, or 8080. Samsung does not provide much info.
The Question: Is this a valid concern? Does anyone know how much this is enforced-- and by whom--the operators or the handset manufacturers?
Thanks for any info..
Antonia

sperkmandl wrote:
There are no other transactions (no other threads, no other applications).
The overall sequence is strictly linear - no concurrency.
The db is nearly empty - it's just a test db.That seems suspicious. Reduce the complexity of what you are doing to see if you can localize it.
But also take a look at firewall rules and even consider the possibility of hardware failures on both ends and in the network infrastructure.

Similar Messages

  • How can i reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

  • Broken Pipe with Non-blocking Socket

    Hello,
    I write a Unix Agent who connect on a Windows Server with socket...
    Working well on Linux but on Solaris my problem is:
    -When my agent is running before server at connection all seems OK: Connect, Select and Getsockopt but when I try to send data I have always EPIPE Signal but I can receive datas from server !
    - When my agent is strarting after the server all it's Ok
    I don't unserstand this appears on Solaris SPARC 8 and Solaris 9 Intel ...
    Please Help is there something special with non-blocking sockets on Solaris ?
    Thanks

    Can't help you much but what I would recommend is that you
    insure that your pipes are opened for both read/write, even
    though you are only going to read or write from it. This insures
    that the pipe does not close down when you hit EOF.

  • How to enable socket connection?

    I have allowed INTERNET permission, but my socket still blocked.
         <uses-permission android:name="android.permission.INTERNET" />
    If I compile apk with -debug tag, then socket connection works, but my application runs very slow.
    And I dont want to publish a release version with all my debug messages.
    What is the standard way to open socket connection?
    Thanks

                   var s:Socket=new Socket();
                    s.connect("ip_address", "port_number");
                    s.addEventListener(Event.CONNECT, function(event:Event):void{
                        trace('connected!');
                    s.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void{
                        trace('error! ' + event.errorID);
                    s.addEventListener(ProgressEvent.SOCKET_DATA, function(event:ProgressEvent):void{
                        var str:String=(event.currentTarget as Socket).readUTF();
    There are examples out there.  Fire up Google Search .

  • Non-blocking socket concurrent limitation?

    I have 2 socket program,one is server side used nio package with JDK1.4.1,the other is client used traditional socket,the client will initialize about 50
    threads trying to connect with server when starting,but only about 15
    can be accepted,these 2 program are runnning in the same computer which
    OS is win2000 professional PC.
    the followd is these code:
    please make a probe with them ,and tell me what's going on?
    server:
    package nio_select_demo;
    import java.io.*;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.util.*;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    public class Server implements Runnable
    // The port we will listen on
    private int port;
    // A pre-allocated buffer for processing data
    private final ByteBuffer buffer = ByteBuffer.allocate( 16384 );
    private ByteBuffer resBuf = ByteBuffer.allocate( 128 );
    Selector selector;
    AddInfo test ;
    public Server( int port ) {
    this.port = port;
    // for (int i=0; i<threadnum; ++i) {
    new Thread( this ).start();
    test = new AddInfo();
    test.start();
    public void run() {
    try {
    // create a ServerSocketChannel
    ServerSocketChannel ssc1 = ServerSocketChannel.open();
    // ServerSocketChannel ssc2 = ServerSocketChannel.open();
    // Set it to non-blocking
    ssc1.configureBlocking( false );
    // Get the Socket connected to this channel, and bind it
    // to the listening port
    ServerSocket ss = ssc1.socket();
    InetSocketAddress isa = new InetSocketAddress( port );
    ss.bind( isa , 60 );
    // Create a new Selector for selecting
    selector = Selector.open();
    // Register the ServerSocketChannel, so we can
    // listen for incoming connections
    ssc1.register( selector, SelectionKey.OP_ACCEPT );
    System.out.println( "Listening on port "+port );
    int n = 0;
    while (true) {
    // See if we've had any activity -- either
    // an incoming connection, or incoming data on an
    // existing connection
    int num = selector.select();
    // If we don't have any activity, loop around and wait
    // again
    if (num == 0) {
    continue;
    // Get the keys corresponding to the activity
    // that has been detected, and process them
    // one by one
    Set keys = selector.selectedKeys();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
    // Get a key representing one of bits of I/O
    // activity
    SelectionKey key = (SelectionKey)it.next();
    // What kind of activity is it?
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
    SelectionKey.OP_ACCEPT) {
    System.out.println( "accept request" );
    // It's an incoming connection.
    // Register this socket with the Selector
    // so we can listen for input on it
    SocketChannel sc = ((ServerSocketChannel)key.channel()).accept();
    System.out.println( "Got connection from "+sc.socket());
    // Make sure to make it non-blocking, so we can
    // use a selector on it.
    //SocketChannel sc = s.getChannel();
    sc.configureBlocking( false );
    // Register it with the selector, for reading
    sc.register( selector, SelectionKey.OP_READ| SelectionKey.OP_WRITE);
    } else if ((key.readyOps() & SelectionKey.OP_READ) ==
    SelectionKey.OP_READ) {
    //ssc.register(selector , SelectionKey.OP_READ);
    SocketChannel sc = null;
    try {
    // It's incoming data on a connection, so
    // process it
    sc = (SocketChannel)key.channel();
    Socket s1 = sc.socket();
    s1.setTcpNoDelay(true);
    System.out.println( "enter processing data" );
    boolean ok = processInput( key );
    synchronized (selector) {
    key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
    // If the connection is dead, then remove it
    // from the selector and close it
    if (!ok) {
    key.cancel();
    System.out.println("dead");
    Socket s = null;
    try {
    s = sc.socket();
    s.close();
    } catch( IOException ie ) {
    System.err.println( "Error closing socket "+s+": "+ie );
    } catch( IOException ie ) {
    ie.printStackTrace();
    // On exception, remove this channel from the selector
    key.cancel();
    System.err.println( "Error raised in this socket");
    try {
    sc.close();
    } catch( IOException ie2 ) { System.out.println( ie2 ); }
    System.out.println( "Closed "+sc );
    else if ((key.readyOps() & SelectionKey.OP_WRITE) ==
    SelectionKey.OP_WRITE) {
    System.out.println("Enter Writing");
    String response = new String();
    if((response=this.test.getInfo())!=null){
    resBuf.clear();
    SocketChannel sc = (SocketChannel)key.channel();
    resBuf = ByteBuffer.wrap( response.getBytes("ISO-8859-1" ) );
    sc.write( resBuf );
    synchronized (selector) {
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    // We remove the selected keys, because we've dealt
    // with them.
    keys.clear();
    } catch( IOException ie ) {
    System.err.println( ie );
    private boolean processInput( SelectionKey key ) throws IOException {
    buffer.clear();
    SocketChannel sc = (SocketChannel)key.channel();
    sc.read( buffer );
    buffer.flip();
    String response = new String("response ok");
    // If no data, close the connection
    if (buffer.limit()==0) {
    return false;
    Charset charset=Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);
    System.out.println(charBuffer.toString());
    System.out.println( "Processed "+buffer.limit()+" from "+sc );
    return true;
    static public void main( String args[] ) throws Exception {
    int port = Integer.parseInt( args[0] );
    System.out.println(port);
    new Server( port );
    cilent:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Client implements Runnable
    private String host;
    private int port;
    private int acport;
    //the size of buffer on how much we write and read per cycle
    private static final int maxWriteSize = 128;
    public Client( String host, int port, int numThreads ) {
    this.host = host;
    this.port = port;
    for(int i =0;i<50;i++){//initialize 50 client threads
    new Thread(this).start();
    public void run() {
    byte buffer[] = new byte[maxWriteSize];
    byte buffer2[] = new byte[maxWriteSize];
    try {
    Socket s = new Socket( );
    InetSocketAddress sa = new InetSocketAddress(host,this.port);
    s.connect(sa);
    System.out.println(s);
    s.setTcpNoDelay(true);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    for (int i=0; i<maxWriteSize; ++i) {
    buffer[i] = (byte)'a';
    out.write( buffer, 0, maxWriteSize );
    int pause = 500;
    in.read( buffer , 0 , maxWriteSize );
    System.out.println( Thread.currentThread()+" wrote "+maxWriteSize);
    String res = new String ( buffer );
    String res2 = new String ( buffer2 );
    System.out.println( res );
    try { Thread.sleep( pause ); } catch( InterruptedException ie ) {}
    } catch( Exception ie ) {
    ie.printStackTrace();
    System.err.println(ie.getMessage());
    static public void main( String args[] ) throws Exception {
    String host = "127.0.0.1";
    int port = Integer.parseInt( args[0] );
    int numThreads = Integer.parseInt( args[1] );
    new Client( host, port, numThreads );

    I have found the reason!!!
    because of system resource limitation,windows can't afford to maintain
    so many concurrent stream-IO,so some socket will be closed.
    I modified the client side code,adding thes segments to client instantialize
    such as :
    public Client( String host, int port, int numThreads ) {
    for(int i =0;i<1000;i++){
    new Thread(this).start();
    try {
    Thread.currentThread().sleep(100);//give system some idle
    } catch (InterruptedException e) {
    /* ignore */
    then the server can accept more than 1000 client request concurrently.

  • Subsequent drop in no. of Socket connections

    Hi All ,
    I have created one application which uses lots of threading and socket connections (Both TCP and UDP).
    I am using Linux Server with following configuration
    1. Quad core processor
    2. 8 GB RAM
    3. Enough bandwidth for 10,000 simultaneous connections
    In this application I need to connect to more than 5000 different Servers at a time. But I could not succeed . The application is quite stable with around 3000-3500 connections and works fine in all aspects.
    Now when I tried to connect to 5000 connections it becomes quite unstable .
    Initially it was showing that Out of memory Error . Then I changed some VM arguments .
    My current VM arguments are
    export VM_ARG=" -Xms64m -Xmx1024m "
    export VM_ARG=$VM_ARG" -Xss75k "
    export VM_ARG=$VM_ARG" -XX:NewRatio=15 "
    export VM_ARG=$VM_ARG" -Djava.net.preferIPV6Addresses=false -ea -Djava.net.preferIPv4stack=true "
    #export VM_ARG=$VM_ARG" -verbose:gc "
    export VM_ARG=$VM_ARG" -XX:+UseParallelGC "Now It doesn't throw the Out of Memory that often but looses the connections quite often .
    I think I could not use the all capabilities of my system . Can any one suggest me some better options
    Thanks in Advance,
    -- Vishal

    You should be able to support around 1,000 - 3,000 threads with an up to date version of Linux.
    I think you have done very well if you have one thread per connection.
    If you want more connections you need to use non-blocking io and then you should be able to cut the number of threads to one or two per CPU.

  • Can somebody explain: blocking socket?

    When a serversocket call accept(), what's it really doing? Does it listen the port for ever until get a request?
    If so, what's the meaning of non-blocking socket? Doesn't it listen the port but wait for a message?
    Anyone, help me.

    when you call accept the thread which calls this is blocked until either
    1) a connection is made
    2) or the socket timeout. The socket timeout is set with the setSoTimeout method
    if there has been no connection made in the timeout time (in milliseconds)
    then an InterruptedIOException is thrown by the accept method and the thread is unblocked, if a connection has been made then this returns a socket.
    Non-blocking socket
    When this is called then the method returns straight away, either with a connection or not, it is up to the user to implement a loop to keep checking for a connection.

  • Writing Java Non-Blocking Socket Server for  Winsock Client

    Hi.
    Im a newbie to Sockets. I need to write a Non-Blocking Socket server (using java.nio) that accepts connection and reads the data sent by WinSock clients, and write them to another winsock client. Its quite intriguing. How do I do that? Is it possible?
    Thanks in advance
    Arun

    Well, in traditional 4.2 BSD sockets, you'd fill up a set of filedescriptors of connections (an array of bits usually), and push that in the read parameter of a call to 'select'. Select then blocks until at least one of the file descriptors become available for reading, or writing if you also made an fd_set full of file descriptors (but you can usually write freely to a socket, so there is not much use for that). Then you start finding out which of these file descriptors have actually become available for reading, and you pass those to a bunch of worker-threads. The advantage is that your set of worker-threads can be quite small, while your number of connections can still be quite large (unless, of course, everyone of your clients start talking all at once, but that is no different from the one-socket-one-thread-model that java.net.* forces upon you).
    In java, the 'select' call is replaced by a call to java.nio.channels.Selector.select(); and then the fishing out of the selected stuff comes from java.nio.channels.Selector.selectedKeys().
    To add a thingy to a selector, use (for example) java.nio.channel.ServerSocketChannel.register(Selector, ops, att);
    whereby the ops parameter is the kind of action you'd like to select this channel for; SelectionKey.OP_READ etc..
    The workerthread bit is also easy to write, but I leave that to you as an exercise.

  • Easy way to non-blocked sockets

    Use JSSE and NIO for a quick way to implement non-blocking communications
    October 22, 2003
    Although SSL blocking operations -- in which the socket is blocked from access while data is being read from or written to -- provide better I/O-error notification than the non-blocking counterpart, non-blocking operations allow the calling thread to continue. In this article, the author will cover both the client and server side as he describes how to create non-blocking secure connections using the Java Secure Socket Extensions (JSSE) and the Java NIO (new I/O) library, and he will explain the traditional approach to creating a non-blocking socket, as well as an alternative (and necessary) method if you want to use JSSE with NIO.
    http://www-106.ibm.com/developerworks/java/library/j-sslnb.html?ca=dgr-jw03j-sslnb

    MORE IBM SPAM Previous discussion
    I find it interesting spam, but thats a matter of taste. If the OP was truly interested in "trying to get new information out there" he would answer the mulitple questions about NIO and especially NIO mixed with traditional Sockets and NIO vs Secure Sockets. These are all on ALT, NIO is of no interest to New to Java folk.
    Given their budget I think IBM could do a better job of publishing their research.

  • Detecting When a Non-Blocking Socket Is Closed by the Remote Host

    Hi,
    Using NIO non blocked sockets how do I detect when a Non-Blocking Socket Is Closed by the Remote Host?
    What I have read is:
    The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.
    I have written a server test program using NIO and an applet connecting to the server program via sockets.
    When I after a successful connection shuts down the browser following happens: The code below comes in an endless loop though mySelector.select returns 0 every time. (The selector is registered for OP_READ). size = 1.
    while (true) {
    int n = mySelector.select();
    int size = mySelector.keys().size();
    if (n == 0) continue;
    Is this an expected result?
    How do I get to know what client has lost connection?
    My environment:
    W2000
    java 1.4.1 build 1.4.1_01-b01
    Browser used: IE 5.0
    Many thanks for your help on this matter!
    Regards Magnus Wistr�m

    What you're doing looks OK to me.
    I wonder whether your thread is being interrupted by Thread.intterupt() somewhere. Try putting a Thread.interrupted() before the select call.
    Sylvia.

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • Non blocking sockets in jdk 1.3.1

    Hello guys
    i am working on client server programs which has socket connections. i am using serversocket and socket objects. At some point i may have multiple clients connected to the server and if one socket gets blocked i am unable to send data to other clients( sockets) also.
    If i know correctly Sockets are of blocking type by default.
    How can i solve this problem in jdk1.3.1?
    IS java.nio.* ther only solution? if yes should i change to 1.4.
    Waiting for u guys reply
    Thanks

    HI you can use a setSoTimeout(timeout) method to set a timeout for read() method in input stream , so since you set a timeout, read() method will block for that amount of time and after it will throw SocketTimeoutExceptions... http://java.sun.com/j2se/1.3/docs/api/java/net/Socket.html#setSoTimeout(int)
    Socket s = new Socket(.....);
    int timeout = 10; //(milliseconds)
    s.setSoTimeout(timeout);
    try {
    int byte = s.getInputStream().read(); // will block for 10 miliseconds or return a byte from stream
    if (byte == -1) ; // stream closed
    } catch(java.net.SocketTimeoutException e) {
    // there is no data to read
    }other way is to use available() method from inputStream and then
    Socket s = new Socket(.....);
    InputStream input  = s.getInputStream();
    int available = input.available(); // it return 0 if there is no data to read or number of bytes available to read
    byte[] buf = new byte[maxBufSize];
    try {
    if (available != 0) {
    s.getInputStream().read(buf,0,available);
    String message = new String(buf,0,available);// if available ==0 then you will get empty string
    } catch(java.io.IOException e) {
    }but you would not be able to find out that client closed connection (because you will never get (-1) from read()), if he closed you always get 0 bytes available, so it is up to you
    Good luck

  • Socket.connect

    I'm trying to write a client application that will connect to a server whenever it becomes available. There are some problems which I hope someone will be able to help, Below is a snippet of the code that makes the connection:
    while(alive){
    try{
    /* part 1*/
    Socket s = new Socket();
    s.setReuseAddress(true);
    s.bind(localAddress);
    /* end part 1*/
    s.connect(targetAddress);
    } catch (Exception e){}
    this seems to works fine. However when I place part 1 of the code outside the while loop. the connection will not be made if the server application is up after my connection thread has started running. Isnt Socket.connect suppose to block until a valid connection is made?
    Also when running my application (with the code above) over a long period of time, I get a OutOfMemoryException (native memory) when the server application is not present. Do I have to specify some other parameters for the JVM to release the native resources allocated for a socket construction or is this just a bug? I am running the application using java 1.6 on RHEL4 2.6.9-34.ELSMP.
    Thank you in advance.

    The thread is respawned when then server application
    drops thus yes the socket will only make one
    connection.Not if you move part 1 out of the loop.If you do that you will attempt multiple connections with the socket, which doesn't work.
    Shouldnt the thread block when .connect() fails?Why? Block doing what?
    Instead i'm getting a connection refused exception.What else should it do?
    No i did not close the socket when I get an exception.You should.
    Should the resources be reclaimed since
    the socket object would have gone out of scope?Eventually.
    I'm running my application on a system with multiple
    network cards thus i need to bind it to the intended
    address.Why? TCP/IP will find the best route if you don't get in its way. Why not let it?

  • Closing socket connection from 2nd thread

    I did some research on different operating systems to find a unique solution how to timeout a blocking recv call in one thread.
    Closing the connection from another thread helps but I found that there are two different methods how to close the connection:
    - either just calling close with the correct linger options
    - call shutdown first and then close
    Unfortunately most platforms work fine with only one of these methods and fail more or less severe with the other method.
    While I think to fully understand the behavior of Windows and Linux, Solaris is still a big question mark for me.
    I have some machines (running Solaris 8, 7 and 2.6) which work well with just closing and crash the system when using shutdown (while having bad luck in the timing of the other peer). And I have another 2.6 machine that behaves the other way around.
    I created a detailed description about the whole problem and my findings in a PDF if you are interested: http://www.webwasher.com/download/notes/timeoutblockingsocketcall.pdf
    Is anybody able to explain how the Solaris implementation works here?
    And does anybody know why I see the differences with the two 2.6 boxes? (I changed patch level and exchanged clib without success.
    Martin

    I have a main program which creates a thread.Why not create a thread once the object has been read.
    The thread would take some time to process this
    object before it accepts another object to be passed
    in from the main program.Threads are used for concurrent execution. If you don't want concurrent execution, don't use additional threads. Have the main program do the reading and execution and then it cannot read another object until it has finished executing the previous one.
    >
    However, I realise that my main program:
    s = new Socket("localhost", 2001);
    will produce a socket connection
    socket connection even if the thread is still
    processing the object. Why is this possible?This is what threads do. It is call multi-threading.
    Initially I thought the thread would lock the socketIt will lock the sockect when you lock it with synchronized. Howver you are creating a new socket each time so even this would not do what you suggest.
    and my main program would not be able to get a socket
    connection until my thread releases the socket.Everytime you call new Socket() it creates a NEW socket. You can open as many socket as the server can handle. (10000+)
    Code in my thread to accept a socket connection:
    server = new ServerSocket(2001);
    ois = new ObjectInputStream(server.accept().getInputStream());I would suggest putting the Socket created by server.accept() into a variable. Otherwise you will not be able to reply to the request, nor will you be able to close() the connection.
    How can I workaround this issue. Hope somebody can help. Thanks.You don't need a workaround, you need to fix the logic of your application.

  • Establishing Socket Connection to a slow or busy server

    Currently, I'm developing an AIM-based BOT application in Java and it requires establishing a socket connection to their free and public server (host: toc.oscar.aol.com, port: 9898).
    About 75% of the time a connection will be successfully established using this:
    oConnection = new Socket("toc.oscar.aol.com", 9898);
    25% of the time when a connection fails (timeout) is due to the server being too slow or busy to respond to the connection request; however, the server will eventually response within 40 to 60 seconds.
    Let me go into details with my findings when attempting to connect to the slow/busy server:
    For experimental purposes, I used the telnet command (via the DOS command prompt: "telnet toc.oscar.aol.com 9898"), the connection will be established usually within 40 to 60 seconds.
    As I said before, the BOT application is developed in a Java environment and when attempting to establish a connection (using Java's Socket), a timeout exception gets raised when it hits the 20-seconds mark. It tells me that the Java Socket has the timeout defaulted to 20-seconds.
    I am aware that we can define the timeout settings using Socket's "setSoTimeout(x)" method; however, it's only good for AFTER a connection is established.
    Now, to sum up my findings � it clearly shows that the DOS' telnet prompt has longer "wait time" before raising any exceptions. As far as Java Socket is concerned, if a connection is not established within 20 seconds, it raises the timeout exception.
    Is there a way to stretch the "wait time" or "timeout" to be longer than 20 seconds for when a socket connection is being attempted?
    Millions of thanks in advance,
    Chad W. Taylor

    Yes, I also tried that option but no cigar. That
    timeout value is an alternative way of using
    setSoTimeout(int).
    I don't think so.
    First the Java documentation would not make sense:
    public void connect(SocketAddress endpoint, int timeout)
    throws IOException
    Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
    Parameters:
    endpoint - the SocketAddress
    timeout - the timeout value to be used in milliseconds.
    Throws:
    IOException - if an error occurs during the connection
    SocketTimeoutException - if timeout expires before connecting
    IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
    IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket
    Since: 1.4
    Second my tests indicate otherwise:
    public class Main {
    public static void main(String[] args) {
    try {
         Socket conn = new Socket();
         conn.connect(new InetSocketAddress(InetAddress.getByName("toc.oscar.aol.com"),9898), Integer.parseInt(args[0]));
         System.out.println("connected under " + args[0] + " seconds");
         conn.close();
    } catch (Exception e) {
         System.out.println("not connected in " + args[0] + " seconds");
         e.printStackTrace();
    Different runs show:
    connected under 120 seconds
    and
    not connected in 20 seconds
    java.net.SocketTimeoutException: connect timed out
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at Main.main(Main.java:21)
    I speculate that the "Connection Request Timeout"
    value is platform dependent because when I use a
    different machine, the request timeout is either
    longer or shorter than 20 seconds.
    That could well be the case.
    So the proper question would be -- where is the Java
    Socket borrowing the timeout value from? The settings
    in Winsock?
    That I don't know.
    Andreas
    Chad

Maybe you are looking for