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.

Similar Messages

  • Printing Word Macro seems too slow

    Hi everyone,
    With the OLE2 Package I am opening a MS Word file, writing data in it. Using a macro I print it (it needs to be a macro because customer wants specific trays on the printer) and then close it using the package again.
    The procedure doing all this seems to be too fast, because it tries to close the file before the macro has finished printing and then I always get an error message (from Word) if I really want to close the document before printing.
    When I printed the file with OLE I could use the Option "no Background printing".
    Is there something similar here?
    How can I be sure that the macro (or the printing) could be executed completely before closing?
    Thanks in advance
    Karine

    Hi Sheikh2,
    I see your HP OfficeJet 8500 is now taking a long time to print a simple word document. Take a look at a few simple changes that could improve the print speed:
    1. Reset the printer, unplug the power cord and pull apart the two pieces of the power supply. Leave unplugged for atleast 60 seconds
    2. Make sure the printer is plugged directly into the wall outlet
    3. Test another wall outlet and see if that improves the speed
    Now if you're still running into slow printing speeds, I would like you to go ahead and start troubleshooting Slow Printing in Windows.
    Please let me know if this was helpful and if your printing is back up to speed now!
    Thank you,
    HevnLgh
    I work on behalf of HP
    Please click “Accept as Solution” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos Thumbs Up" to the left of the reply button to say “Thanks” for helping!

  • Socket creation too slow versus URLConnection

    I'm trying to write a transparent proxy like polipo.
    Polipo is written in C and I want to have the same result in java.
    A simple program that can filter/monitor all connections created and closed by the browser.
    To do so, I've chosen to work with sockets, because that's the only way i know to read and write raw data to and from the browser in a completely transparent way.
    In this moment my code reads and writes every couple of request/response but I've noticed profiling it that the time needed to create the socket is a bottleneck.
    Using URLConnection to create the same connection I need much less time than sockets.
    When socket creation implies 50ms URLConnection implies only 1ms.
    I haven't still understand why.
    I don't want to reinvent the wheel and i've read some old post where this problem was known, but I haven't found the solution.
    Can anyone help me to understand if the approach is incorrect?

    Creating a socket with a host and port parameter implies actually creating the TCP connection.
    Creating a URLConnection just implies creating an object in memory. The TCP connection isn't created until you call getInputStream(), getErrorStream(), or getResponseCode().
    So your measurements are worthless.
    If creating TCP connections is taking excessive time, look to your network and your DNS system.

  • IPad 4th generation charging seems too slow. After 7 hours started at 20%, now only up to 60%.

    iPad 4th generation seems to be charging too slowly. After 7 hours, started at 20%, now at 60%. Is there something I can do to speed things up?

    Do you have the iPad busy doing many tasks while charging, perhaps without your knowledge?  For example, do you have Bluetooth on, even though you are not intentionally using it?  Are you using geofenced reminders (e.g., "remind me to ... when I arrive home")?
    You can stop many tasks from running by double clicking the home button, seeing those tasks thar are currently running (displayed to the right of the home screen display), then swiping toward the top of your iPad the icon above the bottom one that shows the icon as it appears on your screen.

  • Time Capsule with ext HDD seems too slow for ethernet big file transfer

    With new Snow Leopard on a Mac Mini, I have a wired Time Capsule with an external WD USB 2.0 HDD added. While moving files over 802.11N files seem to work fine, a full wired Ethernet connection seems to send the files too fast for the WD external drive to keep up. I get only the first 50Mb before the transfer gets corrupted. Isn't there a handshake that limits the file transmission to allow for the USB drive to stay ahead?
    Has anyone else seen this? Is there a remedy?
    Thanks
    Bill H.

    With new Snow Leopard on a Mac Mini, I have a wired Time Capsule with an external WD USB 2.0 HDD added. While moving files over 802.11N files seem to work fine, a full wired Ethernet connection seems to send the files too fast for the WD external drive to keep up. I get only the first 50Mb before the transfer gets corrupted. Isn't there a handshake that limits the file transmission to allow for the USB drive to stay ahead?
    Has anyone else seen this? Is there a remedy?
    Thanks
    Bill H.

  • LTO 4 seems too slow

    Dear All,
    I purchased one LTO 4 with the SCSI card and cable. I inserted the hardware in SF V880. Now while taking 100 GB backup it takes around 1 hour and 10 minutes. According to the speed given for LTO 4 it was around 80 MB/sec but I did not see the backup in that way. Theoretical the backup must complete in around 20-25 min. Initially the backup with SDLT was around 1 hour and 22 min for the same size of backup. I can gain only 12 min gain that with LTO4 than SDLT. Can anyone please reply me what might be the cause for this slower speed with LTO 4? The backup is slow with both tar and ufsdump.
    Best Regards,
    Bikash

    This question has been asked and answered umpteen times. Please search the forums before posting.

  • 7342 too slow on loading

    HI
    I use 7342, it seems too slow to load parametres to the card between 20 ms and 40 ms : ( i have used canalyzer to check the time with 2 frames like below)
    CANTx_CVI_CMF();// can frame
                                 // Load motion parameters to the FlexMotion controller
                                flex_load_rpm (boardID, axisNum, Vitesse , HOST); 
                                flex_load_rpsps (boardID, axisNum, NIMC_BOTH, acceleration_RPSPS, HOST);
                                // Start motion
                                flex_load_target_pos (boardID, axisNum, targetPosition, HOST);
                                flex_start (boardID, axisNum, 0);
    CANTx_CVI_CMF();// can frame
    is there any option to make that faster ?
    thank you

    20 to 40 ms sounds a bit long but depending on your CPU, chipset and so on it's not extremely extraordinary.
    If you want to reduce the time between two or more moves you should either use blending or contouring. In blend mode you can load the new move constraints for the next move while the current move is still running. With the blend factor you can either decide to accelerate the next move when the first move starts to decelerate (blend factor = -1) or wait for an adjustable number of ms between the moves.
    Contouring allows you to download buffers with position data to the board. To learn more about both features please follow this link. Most of the examples in this tutorial are written in LabVIEW but it works the same way in C.
    Here you can find some C examples (example1, example2) for blending. You will find more examples in the NI-Motion driver installation directory.
    I hope that helps,
    Jochen Klier
    National Instruments Germany

  • Java web start application runs too slow...

    Hello,
    I am new to Java Web Start. I have created a java web start application and when i enable web start from local Execution, then it works perfectly well. But when i upload it on server and then download the application, then it is too too slow...i mean it takes minutes to get the output on clicking some button....my jnlp file is as under:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <jnlp codebase="http://(web server code base)" href="launch.jnlp" spec="1.0+">
    <information>
    <title>ERD</title>
    <vendor>Deepika Gohil</vendor>
    <homepage href="http://appframework.dev.java.net"/>
    <description>A simple java desktop application based on Swing Application Framework</description>
    <description kind="short">ER Deign Tools</description>
    </information>
    <update check="always"/>
    <security>
    <all-permissions/>
    </security>
    <resources>
    <j2se version="1.5+"/>
    <jar href="ERD_1_2.jar" main="true"/>
    <jar href="lib/appframework-1.0.3.jar"/>
    <jar href="lib/swing-worker-1.1.jar"/>
    <jar href="lib/jaxb-impl.jar"/>
    <jar href="lib/jaxb-xjc.jar"/>
    <jar href="lib/jaxb1-impl.jar"/>
    <jar href="lib/activation.jar"/>
    <jar href="lib/jaxb-api.jar"/>
    <jar href="lib/jsr173_api.jar"/>
    <jar href="lib/ant-contrib-1.0b3.jar"/>
    <jar href="lib/jaxb-impl.jar"/>
    <jar href="lib/jaxb-xjc.jar"/>
    <jar href="lib/FastInfoset.jar"/>
    <jar href="lib/gmbal-api-only.jar"/>
    <jar href="lib/http.jar"/>
    <jar href="lib/jaxws-rt.jar"/>
    <jar href="lib/jaxws-tools.jar"/>
    <jar href="lib/management-api.jar"/>
    <jar href="lib/mimepull.jar"/>
    <jar href="lib/policy.jar"/>
    <jar href="lib/saaj-impl.jar"/>
    <jar href="lib/stax-ex.jar"/>
    <jar href="lib/streambuffer.jar"/>
    <jar href="lib/woodstox.jar"/>
    <jar href="lib/jaxws-api.jar"/>
    <jar href="lib/jsr181-api.jar"/>
    <jar href="lib/jsr250-api.jar"/>
    <jar href="lib/saaj-api.jar"/>
    <jar href="lib/activation.jar"/>
    <jar href="lib/jaxb-api.jar"/>
    <jar href="lib/jsr173_api.jar"/>
    </resources>
    <application-desc main-class="erd.screen1">
    </application-desc>
    </jnlp>
    I dont understand the reason. Could you please help me out.
    Thank you,
    Deepika Gohil.

    Check your web server's access logs to see how many requests web start is sending for each jar. After you've loaded the application the first time, for each subsequent launch, if you've got everything configured right, you should only see requests for the JNLP file and maybe some gifs because web start should load everything else out of the cache (if you're using the version-based download protocol). Or if you're using the basic download protocol, then you might see requests for each jar file, but even in this case, if your web server is prepared to evaluate the last-updated attribute for each jar request and for jars that have not changed, respond with no actual payload and a header value of Not-Modified, then that should run almost as fast.
    You might also want to consider changing the "check" attribute of the "update" element from "always" to "background" for a couple of reasons. It should allow your app to start sooner (but this means that you might have to launch once or twice after an update is applied to the web server before the update shows up on the workstation). Also, my impression is that "always" is broken and prevents web start from ever checking to see if your jnlp file has been updated if you launch your app from a web start shortcut - launching from a browser is less likely to have this problem, depending on how often your browser is configured to check for updated resources.

  • HT1338 My mac is becoming too slow. It takes long to open word documents, pdf files or excel documents or even safari. Can anybody suggest something? I have tried to reduce the number of open applications, but does not seem to work.

    My mac is becoming too slow. It takes long to open word documents, pdf files or excel documents or even safari. Can anybody suggest something? I have tried to reduce the number of open applications, but does not seem to work.

    Hi ...
    Checked to see how much free space there is on the startup disk lately?
    Right or control click the MacintoshHD icon. Click Get Info. In the Get Info window you will see Capacity and Available. Make sure there's a minimum of 15% free disk space.
    Freeing Up Hard Disk Space - Mac GuidesFreeing Up Hard Disk Space - Mac Guides
    If disk space is not the issue, booting in Safe Mode deletes system caches that may help.
    A Safe Mode boot takes longer then a normal boot so be patient.
    Once you see the Desktop, click the Apple menu icon top left corner of the screen.
    From the drop down menu click Restart.
    See if that makes a difference ...

  • I just bought MacPro 15", i7, Quad-Core, upgraded to 8GB RAM. Its responding to slow to poen applications e.g. word, ppt, chrome etc. reboot is too slow. Dont think its working so fast. Dosenot seems to be worth to money paid. What to do?

    I just bought MacPro 15", i7, Quad-Core, upgraded to 8GB RAM. Its responding to slow to poen any applications e.g. word, ppt, chrome etc. reboot is too slow. Dont think its working so fast. Dosenot seems to be worth to money paid. What to do? Not happy with Mac.

    Sandeep Goyal
    Jul 8, 2012 2:26 AM 
    Is is possible to install Win 2007 in MacPro (retina display) with USB (2.0 or 3.0) as new Mac retina display lacks DVD.
    MacBook Pro with Retina display, Windows 7 
    They have been calling their notebook a MacPro for a year. Or is it this?
    https://discussions.apple.com/thread/4463661

  • 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();

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

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

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

  • Error message trying to reproduce the demo songs on the pack. A message appears: The disk is too slow o there is an overloaded. My system is in Spanish so maybe the message is not exactly like this in English but I am sure you will get the idea. Thanks!

    When I try to reproduce the demo songs that comes with the Logic Studio pack a message pop out : The disk is too slow or there is an overload.
    Any help, please?

    spheric, thanks a lot!!!
    You are right, as soon I copied the songs to the HD all of them works perfect!
    Thanks a lot!!!

Maybe you are looking for

  • User defined form usr disapperas from design console (OIM 9.1.0.2)

    Hi, I have imported usr.xml from one environment to another, and usr form disapperas from design console. Also getting an error message while importing xml. java.util.zip.ZipException: error in opening zip file DEBUG,16 Dec 2011 10:35:05,383,[XELLERA

  • Saving a file in Vi creates same file but with ~ added [SOLVED]

    Hi, I'm not sure if I pressed a key combination, but when I save a file in Vi I get another file that has the same name as the original file but with the ~ character added to the end of the filename.  For example, if I edit foo.txt and save it, then

  • S.M.A.R.T. say my drive is failing

    My computer has just shown the following S.M.A.R.T. message and I have verified it using Disk Utility: If you see a message saying the disk has a fatal hardware error, the disk has an irreparable hardware problem that can't be fixed by Disk Utility o

  • Macbook pro doesn't see lexor 16gb usb memory stick.  (Windows PC does see it)

    Heading says it all.  I'm baffled.  Windows PC sees the memory stick but my MacBook Pro doesn't. Plese help. TJ

  • Vertical Display on Ext. Monitor

    I bought an HP w2207 monitor (which totally rocks the house, by the way), and it comes with the handy feature of rotating vertical for viewing webpages, editing photos, ect. At the electronic's store, the monitor was connected to a Vista machine and