Java NIO and sockets in 1.4.1FCS

Hi,
I have built a client server system using the new 1.4 java.nio packages. In 1.4 everything worked fine, yet in 1.4.1 FCS it definitely does not. The process is as follows.
Everything work in non-blocking mode:
- Server receives connection and accepts it, the new SocketChannel is put in non-blocking mode and registered with the same selector as the server.
- New SocketChannel waits for data from the client so it waits for OP_READ from the selector. All it gets is OP_WRITE, OP_CONNECT. With 1.4 it received OP_READ, OP_WRITE.
I tried adding a call to finishConnect, but that didn't help.
Anyone have any thoughts about this?
Thanks,
Mike.

The code in the bug report is incorrect. The key will of course always be writable if you do not write anything to the socket! And since it is writable the readable part of the code will never be executed (its in an else-statement). When you are not interested in the OP_WRITE, change the ops on the selection key.

Similar Messages

  • Java.nio and databases

    Please, need help.
    I'm using java.nio to get large files contents (txt) and need to put these data into MSSQL SERVER 2000 database tables. NIO have capabilityies to get data and transfer directly to the tables? If so, how can i do it?
    Thanks a lot
    Aloisio

    ChuckBing, i'm connected with database trough JDBC yet and i can retrieve data meaning my connection is OK.
    I'm able to read data from a txt file (250mb large) trough MappedByteBuffer and write into another with the same size and content. It's working fine.
    My question is if i can read the txt file and, instead write the data into another txt file, put these data into a table.
    Thanks for your reply

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem with Java Proxy and Socket Connection

    Hi Gurus!!
    I have developed a Java Proxy that connects via socket with a Server Socket application. This Server Socket application accepts more than one connection at the same time.
    When I connect the first time from my Java Proxy, the connection is correctly established. When the first connection opened, if a try a second connection, this is not established.
    I use "new Socket(SocketServer,SocketPort);" to open the connection.
    I think that all time the Java Proxy is trying to open the same connection, and this is a problem.
    Is there a way to indicate to the server that is a new connection and that the existing connections remain?
    Anybody could help me, please?
    Thanks and regards,
    Manuel Míguez.

    Sorry!!!!i must give you more information.
    The error which i have when i push the submit button is
    HTTP Status 404 -
    type Status report
    message
    descriptionThe requested resource () is not available.
    GlassFish Server Open Source Edition 3.0.1
    My thought is that the error is in this line
    String connectionURL = "jdbc:mysql://localhost/mybooking";in mysql when i write this code then the table opens with no problems:
    mysql>show databases;
    mysql>usebooking;
    mysql>showtables;
    mysql>describe booking;Furthermore i have added in my web application the library mysql JDBC driver my-sql-connector-java-5.1.6.bin.jar
    Edited by: 813355 on Nov 22, 2010 1:50 AM
    Edited by: 813355 on Nov 22, 2010 2:00 AM

  • Java WD and Socket Communication

    Hi,
    Is it possible to use Java Socket Communication with Java Web Dynpro. Or if not what is the best approach to have a Java Socket program integrated with a Web Dynpro Communication.
    Basically, I have an application which provides API for communication via Java Sockets.And this needs to be integrated in our SAP application.
    Thanks,
    CD

    Hi,
    You are currently using JCO to "Connect to a Remote System" - JCO will connect to a back-end with the main purpose of "executing BAPI's" in it.
    When you move to WebDynpro, you have what SAP calls Adaptive RFC Model - this will create a "Model Entity" in you WD Project that will do the same thing your JCO does.
    Assume your JCO now calls "BAPI_GET_FLIGHTS", to return the Flights that are currently available - In your newly create WDP Project, you will manually specify what back-end you wanna use when "Importing" and you will tell also the BAPI name. WDP will generate the class structure that you need in order to execute that function.
    JCO is what SAP created to execute BAPI's. JCO can be used by any "Java" like application that needs to connect to the back-end. But when you move to WDP, you don't need to use this anymore - You will use WDP Models.
    Youi will still need your JCO Destinations created in the Application Server, so behind the scenes WDP creates a "layer" so you don't need to code the JCO calls manually.
    Regards,
    Daniel

  • Java Nio and http proxy

    Hello,
    I would send a http request through a http proxy with a Nio Client. So I wrote by hand the
    http request :
    buffer.append("HTTP/1.1\n");
    buffer.append("Content-type: text/xml\n");
    Then I send this request with a Nio Client but the request doesn't pass.
    Can you help me ?

    I use tcp to send my request with a nio Client. The header of my http request :
    StringBuffer buffer = new StringBuffer();
    buffer.append("POST ");
    String path = "/";
    buffer.append(path + " ");
    buffer.append("HTTP/1.1\r\n");
    buffer.append("Content-type: text/xml\r\n");
    buffer.append("Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\r\n");
    buffer.append("Host: 10.194.55.23:80\r\n");
    buffer.append("Connection: keep-alive\r\n");
    buffer.append("Content-Length: 0\r\n");
    buffer.append("\r\n");

  • Help "ascending" to Java NIO

    Hello there.
    I've been using Java for quite some time, but the few really networked client/server applications I have used, have used java.io and java.net. Now, even I have heard the rumours about Java NIO, and I am curious. I have tried reading up and down the API on java.nio.* , but I must say I am still kind of confused.
    Basically, I am looking for some example code, or a thorough explanation of how all the classes and components come together to form efficient asynchronous non-blocking I/O.
    What I picture is a server over TCP/IP meant to handle 100+ clients, written with an emphasis on performance. Think MMORPG, I guess (no no, I am not ambitious enough to want to write one, but I can imagine that gives a good analogy of how I would have the communication set up). The server needs to quickly figure out which clients need to be handled at any given time, with as little overhead or reduntant iteration as possible.
    Ok, I am asking alot perhaps.. I just wonder if anyone could offer links to example source-code, write something to show me, or basically just try to explain to me how this all works.
    I would be very very grateful if anyone stepped up to the plate.
    Thanks,
    -Terje

    Take a look at my thread Taming the NIO Circus. It starts with simple examples of a single thread echo server and a swing client.

  • Announcement: Java NIO Framework

    Hi all,
    After reading Ron Hitchen's book "Java NIO" and watching his presentation "How to Build a Scalable Multiplexed Server With NIO" at the 2006 JavaOne Conference, I implemented a framework based on his ideas.
    Here is the website: http://nioframework.sourceforge.net/
    I would be very glad if you could take a look and tell me what you think about it.
    Regards and thanks for your input!
    Ronny Standtke
    PS: I will add dukes to this topic and spend it for contributors (found bugs, hints, ...).

    Finally I found the time to write some benchmark programs for the NIO Framework and take a look at the MINA API.
    If you download the latest NIO Framework release you can run the plaintext benchmark as follows:
    Start the benchmark server (this is just the echo server without any session debugging output or logging) with the following command:
    java -cp nio_framework-0.9.3_all.jar ch.unifr.nio.framework.examples.BenchmarkServer 8080
    Then start the benchmark client with the follwing command:
    java -cp nio_framework-0.9.3_all.jar ch.unifr.nio.framework.examples.BenchmarkClient localhost 8080
    On my machine the resulting bandwidth is around 80 MB/s.
    And now to MINA:
    I used the very simple echo server example from the MINA project and just removed the logger from the chain. You may download this package from here (it includes all relevant source code):
    http://nioframework.sourceforge.net/mina_echo_server.jar
    You can start this server with the following command:
    java -jar mina_echo_server.jar
    If I run my BenchmarkClient against the MINA echo server the resulting bandwidth is only around 20 KB/s!? That is about 4000 times slower.
    Is MINA really THAT slow? I seriously doubt that. Are there any stops that I have to pull to get a higher bandwidth with MINA?

  • 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.

  • Socket seems too slow...maybe java.nio?

    Hello
    In our system I have to receive Multicast Packets repeats very quick(1-5 ms). I have to link them one after an other in the order they sent. And if I miss a packet, something will go wrong...
    I have to listen to different IPs and I use different threads for different IPs. If I use only one thread (and listens to only one IP) everything seems ok.
    But if I starts listening to an other ip too, I miss 2 packets in a row, or only one if I turn off parsing the message (XML).
    Here is the code I use in the Threads:
    try{
                   socket = new MulticastSocket(port);
                   socket.setSoTimeout(1000);
                   inetAddress = InetAddress.getByName(ip);
                   NetworkInterface nInterface=
    NetworkInterface.getByName(networkInterface);
                   if(nInterface!=null)socket.setNetworkInterface(nInterface);
                   socket.joinGroup(inetAddress);
              catch(IOException ioe){
                   logger.error(ioe.getMessage(), ioe);
    return;
              try{
                   while (!interrupted()) {
                        try{
                             byte[] buffer = new byte[1480];
                             packet = new DatagramPacket(buffer, buffer.length);
                             socket.receive(packet);
    parse(buffer);
                        }catch(SocketTimeoutException stoe){
                             //     DO NOTHING
                        }catch(IOException ioe){
                             logger.error(ioe.getMessage(), ioe);
              }finally{
                   try {
                        if(socket!=null){
                             socket.leaveGroup(inetAddress);
                   } catch (IOException ioe) {}
    Every Thread has its own parsing object.
    Any tips, what is wrong?
    Maybe java.nio could solve the problem somehow. There is a sample server in [Java Home]/sample/nio/server and it suggest that there are quicker methods to receive messages from different IPs (maybe Blocking/Pooled-Thread Server). But I can't understand the API and the Sample while I was reading it (20-30 minutes).
    Could it be quicker? Does it worth toying with the idea?
    Thanks:
    Bence

    In our system I have to receive Multicast Packets
    repeats very quick(1-5 ms). I have to link them one
    after an other in the order they sent. And if I miss
    a packet, something will go wrong...There is no guarantee anywhere in the system that you won't miss a datagram. UDP doesn't make such guarantees. If you need all the packets you will have to build ACK or NACK into your protocol.
    You can alleviate the problem by running a very large socket receive buffer. But you can't eliminate it. Rethink this.
    NIO is not significantly quicker for applications like this, it is more scalable.

  • Java NIO, ByteBuffers and Linksys router

    I have a client server app/game that uses NIO for communication sending ByteBuffers. On a LAN with 5-8 users it runs great. On the internet, through a Linksys router, with one user, it has a blip. I get all my data transmissions except for one buffer. Whenever I chat the buffer contains a size, an int typeID and the encoded string for chat. This particular buffer never makes it to the client on the outside of the router. I have a port forwarded and regular tcp/ip java io sockets stuff works fine. As does al lof the other NIO buffer traffic for locational data, login in and out, etc... ANy thoughts??

    But not sure what would be the performance of those clients?? when compared to Java NIO performance....Telnet isn't a high-performance protocol anyway. Don't worry about it. Use existing code. Get it working. Measure. If you have a performance issue, then worry, while at least you have something you can deploy. It won't be a problem. The router is there to route, not to talk high-speed telnet.

  • Socket disconnection event not being reveived java.nio

    Hi All
    My question is as below
    i am using java.nio package + win 2K + jdk1.4.1_02
    I have a Server accepting socket connection and is configured
    in Nonblocking mode.
    -The server receives (selector) events (accept event)
    when a client requests for a connection .
    -The server is getting read and write events when
    client wants to read and write
    -The server gets a read event when the client disconnects
    My only problem is that the Server is not getting any events
    when the client disconnect due to network break down
    for EX when the network connection breaks the client disconnects
    but the server selector is not getting any events
    I am storing the client Socket objects in a Hash Table and
    if i execute the .isConnected() method it returns true
    even though the the client is down
    The only work around is to try to read and write on the socket
    i get an IO exception and am able to make out that the
    client is disconnected
    But this is not desirable for my client
    as client modification to give any kind of echo is not possible and
    a read /write event will cause problem.
    Can any one tell how to detect client side disconnection
    with out Read and Write on the client socket
    I get an socket Exception when the socket is in Blocking IO and is blocked on read/ write but I am facing this problem in NonBlockingIO
    Regards
    Avinash

    int ct = read.selectNow();
    if (ct > 0)
    Set readyKeys = read.selectedKeys();
    Iterator i = readyKeys.iterator();
    while (i.hasNext())
    SelectionKey key = (SelectionKey) i.next();
    i.remove();
    if (key.isReadable())
    SelectableChannel nextReady = (SelectableChannel) key.channel();
    SocketChannel sc = (SocketChannel) key.channel();
    int rd = sc.read(buffer);
    // Link is dead
    if (rd == -1)
    key.cancel();
    key.attach(null);
    nextReady.close();
    continue;
    // Process your data
    catch (Exception e)
    e.printStackTrace();

  • NIO and traditional sockets

    I have a little server that I was porting from traditional thread per socket programming to NIO. The first thing I ported was the Listen-Accept loop. This worked well but the resulting sockets obtained from
    SocketChannel.socket()
    have very strange behaviour with respect to flush. I send the data by
    out.write(data);
    out.flush();
    where out is the BufferedOutputStream. The data doesn't get sent until the next input arrives on the Socket. If I change to using just old style I/O or completely NIO the problem goes away.
    I found several bug reports on NIO and flush, but they all seem to be considered Feechures by SUN.

    Thanks for posting the link to your NIO code. I downloaded the src-raining-1.2pre1 source and took a look. I noticed that you still have some doubts about how OP_WRITE works. This piece of code will definitely have problems.
        public void setSendData(ByteBuffer data) {
            this.write_pending = true;
            wBuffer = data;
            //RK modified on 20031008 23:19:39 - NOOO
                    //registerChannel(selector, channel(), SelectionKey.OP_WRITE);
            // RK modified on 20031009 23:15:00 adding write interest
            SelectionKey sk = sc.keyFor(selector);
            int ops = sk.interestOps();
            sk.interestOps( ops | SelectionKey.OP_WRITE);
            selector.wakeup(); // is this required or not ???
        }The sk.interestOps will block if there is an active select. If there isn't an active select you don't need the wakeup. The only way to make this work properly in 1.4.2 is to build a queue of runnables that set interestOps and execute them just before or after the select. Also the setting of OP_WRITE in that code won't handle the case where the network exerts flow control on the channel. The correct setting of OP_WRITE is
    - set interest in OP_WRITE when the socket is connected
    - remove interest as soon as you successfully write all the data in a buffer
    - add interest only when you write less bytes than requested.
    My post Taming the NIO Circus provides an example of this in the swing based client. I posted this in response to Java.nio. SelectionKey interestOps(int) method blocks

  • 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.

  • Selecting between java.io and java.nio

    Hi,
    I'm a bit confused between java.io and java.nio. What sre the major differences between these two?
    In areas are these best applicable?

    The java.nio package improves on the basic Java I/O that was available prior to JDK 1.4.
    It is designed to interoperate more natively with the underlying file handles (sockets, open files etc) to achieve better performance.
    The improvements include true non-blocking I/O, better buffer management, character-set support, channels (similar to Occam's channels) and selectors, and some other ancillery stuff. Most of these classes are designed to be inherently threadsafe.
    There are some examples here:
    http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/index.html
    However, if you are still a beginner with file or network I/O, its better if you start with the simple I/O first. You'll appreciate the NIO improvements better afterwards.

Maybe you are looking for

  • BAPI for Process order creation (COR1)

    Hi All, Can any please help me to find a BAPI for creating a process order which is done normally by transaction code u201CCOR1u201D. Thanks in advance. Kind Regards, Abhi.

  • Nokia 6700 Classic Voice DIalling Tags

    I have just puchased a Nokia 6700 as a modern replacement to my faithful still functioning but somewhat battered 6230i. However I find that it seems that you can no longer attribute voice tags to individual entries for use in my handsfree car kit. On

  • Installing PS CS3 with Win 7 64 bit

    I will soon receive a new desktop pc with Win 7 64 bit as the OS.  I plan on installing my existing copy of Photoshop CS3 on this machine.  Are there any issues I need to be aware of in order to get a clean installation? Thanks, Ken Some machine spec

  • How to decide buffer sizes for specific size of RAM

    Hi sdners. Generally, how can we decide the buffer sizes which are shown in the ST02 screen. suppose we have 100GB ram /5GB ram,  then how can we decide the related buffer sizes...and generally which buffer takes more place in the RAM Thanks in advan

  • IPhoto 6 delete photos and count increases

    I'm deleting photos from the library (not an album), and have emptied the trash. But the photo count keeps increasing. Help!