Controlling sending rate over UDP socket

Hello,
After some NIO study, i finally managed to send and receive UDP data from a single thread. Here is my code
so far:
try {
      DatagramChannel channel = DatagramChannel.open();
      channel.configureBlocking(false);
     channel.socket().bind(localAddress);
      boolean flag = true;
      int LIMIT = 1000;
      Selector selector = Selector.open();
      channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
      ByteBuffer buffer = ByteBuffer.allocate(4);
      int n = 0;
      int numbersRead = 0;
      while (flag) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
          Iterator iterator = readyKeys.iterator();
          while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isReadable()) {
              buffer.clear();
              channel.read(buffer);
              buffer.flip();
              numbersRead++;
            } else if (key.isWritable()) {
              n = queue.poll();
              buffer.clear();
              buffer.putInt(n);
              buffer.flip();
              channel.write(buffer);
              System.out.println("Wrote: " + n);
             if (n == LIMIT) {
                // All packets have been written; switch to read-only mode
                key.interestOps(SelectionKey.OP_READ);
    }  // end try
    catch (IOException ex) {
      System.err.println(ex);
    }  // end catchThis thread both receives and send integers from/to my UDP echo server. Another thread acts as data generator and add data to ConcurentLinkedQueue. The sending thread poll the data from the queue and sends it.
Right now, the thread is sending at full speed.
I would like to know how i can control the sending rate ?
I would like to be able to specify a given rate like 50 packets per second, 100 packets per seconds...?
Of course i can always slow down the sending part by adding Thread.sleep(someValue) before or after sending..
but this way i am not sure what is the real rate achieved.
any advises would be welcome.
thanks
sepi
Edited by: sepi_seb on Dec 17, 2007 6:50 PM

hi
thanks for your reply.
I have some difficulties calculating the amount of time i need to sleep to achieve a proper sending speed.
basically it takes 16ms to send 20 requests so 1250req/s. Hoe can i regulate this accurately.
I added this kind of code in my sending part: Every 50 requests i execute this code.For some reason i get a divided by zero exception at the line marked in bold.
it happens at the second execution of this code.
     if(count == 50){
              count = 0;
              elapsedTime = System.currentTimeMillis() - startTime;
              System.out.println(elapsedTime);
              *sendingRate = (50 * 1000) / elapsedTime;*
              System.out.println("sending at:" + sendingRate + " req/s");
              if(sendingRate > speed){
                long diff = sendingRate - speed;
                long sleepTime = (diff * elapsedTime) / 50;
                try {
                  Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
      }any comments are welcome
thanks
sebastien

Similar Messages

  • Sending images over network socket

    I'm working on a java web server. So far i have managed to get it to send html documents sucessfully to the client web browser, using a BufferedReader, and a PrintWriter object.
    But how should i send images over the socket? using this method doesn't work. Any suggestions?
    Thanks in advance.
    hornetau

    I did it first. You may pay me $10 and get XM2 WebServer 1.2 from my company.
    Ok, I'll help ya out here...
    HTTP protocol in Internet Explorer is "juiced up" meaning that it does not require HTTP data to be correctly sent. To send an image to be deisplayed...
    <html>
    <img src="theImage.gif"></img>
    </html>
    Now, the server will see a GET request like this...
    GET /theImage.gif HTTP/1.1
    Accepts: Image/jpeg, Image/gif, ...
    Your web server (in the IE case just needs to send)...
    output.println(data);
    The data object is a string, that represents the contents of the image.
    To do that, just get the correct File object, connect reader to it, then loop it
    until the reader is no longer ready (reader.ready() != true), as it loops, just append
    the readLine() command to the end of the data string and it will be ok.
    Now this works on IE just fine, using vary small file sizes due to it being loaded directly into
    memory. Casing problem if your app has only 500K of memory and the file size is 700K, 500-700=-200K, so use only small file sizes with this method.
    There is also the URLConnection and HttpURLConnection classes to use that will do this better, but
    they dont have any real way of getting the file's data - that's still YOUR job.

  • Sending voice over UDP with JavaSound

    Hello,
    do anybody know how to send voice over UDP?. I have .wav files and I want to send them over UDP. If you have an example of this, send me it please. All the examples that I have seen only send one or to lines of text, but I need to know if I should convert the frames to bytes to be sent.
    Thank your help

    Hello,
    do anybody know how to send voice over UDP?. I have .wav files and I want to send them over UDP. If you have an example of this, send me it please. All the examples that I have seen only send one or to lines of text, but I need to know if I should convert the frames to bytes to be sent.
    Thank your help

  • Sending data over and socket

    when i send messages over socket and receive it using [line = in.readLine()/code]
    if there is a \r\n it stops and makes u have to use readLine again to get the rest of the message
    is there a way to send the message so it totally ignores the \r\n and i can just use readLine once to receive my complete string in one go
    as this newline thing is very annoying
    thanks :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I assume in is of type BufferedReader? If so, that is the definition of readLine.
    Other options:
    You can use java.util.Scanner to scan until the next delimiter, which you can set.
    You can use readUTF/writeUTF defined in interfaces DataInput/DataOut by
    using classes DataInputStream/DataOutputStream or ObjectInpuitStream/ObjectOutputStream.
    If you are using object stream, you could define any serializable objects you
    like for transmission.

  • Send ArrayList through UDP socket

    I have the following 2D ArrayList
    ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();How is it possible to send it through a UDP socket and then get it back?

    Apart from adding implenents Serializable after the class name what else i have to do in order to add the arraylist to the datagramSocket?
    For simple sockets i have found this
    http://java.sun.com/developer/technicalArticles/ALT/sockets/ but
    but it doesn't work for DatagramSocket
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); throws an error "The method getOutputStream() is undefined for the type DatagramSocket"
    Edit: It seems this site has the solution
    http://www.nada.kth.se/~bishop/resources/javaSerial/index.html
    Message was edited by:
    [email protected]

  • Passing info over a socket

    lets say I read in a vector from a file on a server, and I want to read the vector into another vector on the client side. I know the clients objectinputstream is the servers objectoutputstream, but how to I send objects over a socket connection.
    Thanks.

    client:
    public class Client implements Serializable
    Socket socket;
    // PrintWriter out;
    Vector userPass, guestBooks;
    BufferedReader inp;
    public Client()
    try
    socket = new Socket("13", 60);
    // out = new PrintWriter(socket.getOutputStream(), true);
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            Object o1 = in.read();
            Object o2 = in.read();
            in.close();
    catch(IOException e)
    e.printStackTrace();
    Server:
    public class Server implements Serializable
    ServerSocket sock;
    Socket clnt;
    File file1, file2, file3;
    FileInputStream fis1, fis2, fis3;
    Vector userspass, guestbooks;
    public Server()
    try
    sock = new ServerSocket(60);
    System.out.println("Listening on: Port 60");
    clnt = sock.accept();
    file1 = new File("user.txt");
    file2 = new File("guestb.txt");
    fis1 = new FileInputStream(file1);
    fis2 = new FileInputStream(file2);
    ObjectInputStream in1 = new ObjectInputStream(fis1);
    ObjectInputStream in2 = new ObjectInputStream(fis2);
    userspass = new Vector();
    guestbooks = new Vector();
    try //read in the object from the file to the vectors
    while(in1.readObject()!= null)
    userspass.add(in1.readObject());
    while(in2.readObject()!= null)
    guestbooks.add(in2.readObject());
              // here you want to send the vectors to the client?
              ObjectOutputStream out = new ObjectOutputStream(clnt.getOutputStream());
              out.write(userspass);
              out.write(guestbooks);
              out.close();
    catch(Exception ex)
    ex.printStackTrace();
    sock.close();
    sock.close();
    catch(IOException e)
    e.printStackTrace();
    }Something like that. I have never used Object streams myself, so there's probably more to it (like making sure that vectors are serializable, and/or the contents in them). Also I'm not sure if closing the Object stream will close the socket's I/O stream also.... something for you to test and see.
    HTH,
    Radish21

  • Increase UDP sending size over 64k bytes and get error -113,sending buffer not enough

    Dear all,
    I have a case that I must send a data over 64k bytes in a socket with UDP . I got a error-113 shows "A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.".I searched for this issue and got the closest answer as below:
    http://digital.ni.com/public.nsf/allkb/D5AC7E8AE545322D8625730100604F2D?OpenDocument
    It said I have to change buffer size with Wsock.dll. I used the same mathod to increaes the send buffer to 131072 bytes by choice optionname to so_sndbuf (x1001) and give it value with 131072 and it worked fine without error. However I still got an error 113 while sending data with " UDP Write.vi ". It seems UDP write.vi reset the buffer size? Are there any other things cause the error?
    I attached example code. In UDP Sender.vi you can see I change send buffer size to 131072 and send date included a 65536 bytes data.There is also a UDP receiver.vi and there is some missing VI which you can get from the LINK. But it's not necessary.
    Attachments:
    UDP Sender.vi ‏14 KB
    UDP Receiver.vi ‏16 KB
    UDP_set_send_buffer.vi ‏16 KB

    The header for a UDP packet includes a 16 bit field that defines the size of the UDP message (HEADER AND DATA)
    16 bits limits you to a total size of 65635 bytes, minus the header sizes; a minimum of 20 bytes are required to define an IP packet and 8 bytes for UDP leaving an effective data payload of 65507
     bytes.
    LabVIEW is not the issue...
    http://en.wikipedia.org/wiki/User_Datagram_Protocol#Packet_structure
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • How do I send an Image over a socket ?

    I'm trying to get the output from my webcam and send that data out to a socket. Now the output from the webcam is running I'm just not sure how to send it out over the socket.
    Server.java
    import java.io.*;
    import java.net.*;
    public class Server {
       public static void main(String args[]) {
         ServerSocket serverSocket = null;
         boolean listening = true;
         try {
         serverSocket = new ServerSocket(1354);
         System.out.println("Listening for Connections...");
         } catch (IOException drr) {
         System.out.println("Error Listening :" + drr);
         System.exit(-1);
         try {
         while(listening)
         new ServerThread(serverSocket.accept()).start();
         } catch (IOException er) {
         System.out.println("Error Creating connection:" + er);
         try {
           serverSocket.close();
         } catch (IOException err) {
         System.out.println("Error Closing:" + err);
    }When a connection is made it will start the webcam and send the image.
    ServerThread.java
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    public class ServerThread extends Thread {
        public static Player player = null;
        public CaptureDeviceInfo di = null;
        public MediaLocator ml = null;
        public JButton capture = null;
        public Buffer buf = null;
        public Image img = null;
        public VideoFormat vf = null;
        public BufferToImage btoi = null;
        public ImagePanel imgpanel = null;
        private Socket socket = null;
        Image blah;
        PrintWriter out = null;
        public ServerThread(Socket socket) {
         super("ServerThread");
         this.socket = socket;
        public void run() {
         try {
             out = new PrintWriter(socket.getOutputStream(), true);        
             imgpanel = new ImagePanel();
                 String str1 = "vfw:CompUSA PC Camera:0";
                 String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
                 di = CaptureDeviceManager.getDevice(str2);
             ml = new MediaLocator("vfw://0");
                try {
               player = Manager.createRealizedPlayer(ml);
                 } catch (Exception npe) {
               System.out.println("Player Exception:" + npe);
                player.start();
             Component comp;
             if ((comp = player.getVisualComponent()) != null) {
               // Grab a frame
               FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
               buf = fgc.grabFrame();
               btoi = new BufferToImage((VideoFormat) buf.getFormat());
               //Send the image over the socket
               out.println(btoi);
         } catch (IOException e) {
             System.out.println("It bombed:" + e);
        public static void playerclose() {
           player.close();
           player.deallocate();
      class ImagePanel extends Panel {
        public Image myimg = null;
        public ImagePanel() {
        public void setImage(Image img) {
          this.myimg = img;
          repaint();
        public void paint(Graphics g) {
          if (myimg != null) {
            g.drawImage(myimg, 0, 0, this);
      }The output I get from running the server is this:
    BufferedImage@c9131c: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Now how can I turn this into an image If this output is correct?

    HUH?
    I got the one to send the images over the network. I'm now trying to get the exact feed of the webcam and sending that over the network. This is alot more difficult to accomplish but I did see where I messed up my process of sending the images was just having to save the file then open it up put it in a byte array then send that over the network to the client. Once it was at the client i was able to re-construct it and throw it up in the frame. The only problem was lag. So this tells me it would be much more faster if instead of saving the file to send the client and having to reconstruct the image I should just send the webcam feed i used to make the image.
    eh, I guess I didn't need any help.
    Hey no offense or anything but you really have to learn how to spell better.

  • Detect "end of file" while send n numbers files over a socket?

    Hi!
    I�m trying to find a way to detect "end of file" while send n numbers files over a socket.
    What i'm looking for is how to detect on the client side when the file i�m sending is downloaded.
    Here is the example i�m working on.
    Client side.
    import java.io.*;
    import java.net.*;
    public class fileTransfer {
        private InputStream fromServer;
        public fileTransfer(String fileName) throws FileNotFoundException, IOException {
            Socket socket = new Socket("localhost", 2006);
            fromServer = socket.getInputStream();
            for(int i=0; i<10; i++)
                receive(new File(i+fileName));
        private void receive(File uploadedFile) throws FileNotFoundException, IOException {
            uploadedFile.createNewFile();
            FileOutputStream toFile = new FileOutputStream(uploadedFile);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fromServer.read(buffer)) != -1) {
                toFile.write(buffer, 0, bytesRead);
        public static void main(String[] args) {
            try {
                new fileTransfer("testa.jpg");
            } catch (Exception ex) {ex.printStackTrace();}
    }Server side.
    import java.io.*;
    import java.net.*;
    public class fileTransferSend {
        Socket serv = null;
        OutputStream toClient;
        public fileTransferSend(String fileName) throws FileNotFoundException, IOException {
            StartServer();       
            for(int i =0; i<10; i++)
                send(new File(fileName));
        public void StartServer() throws IOException {
            ServerSocket ssocket = new ServerSocket(2006);
            System.out.println("Waiting for incomming");
            serv = ssocket.accept();
            System.out.println("incomming");
            toClient = serv.getOutputStream();
        private void send(File f) throws FileNotFoundException, IOException {
            if(f.exists() && f.canRead()) {
                FileInputStream fromFile = new FileInputStream(f);
                try {
                    byte[] buffer = new byte[4096]; // 4K
                    int bytesRead = 0;
                    System.out.println("sending: "+f.getName());
                    while ((bytesRead = fromFile.read(buffer)) != -1) {
                        toClient.flush();
                        toClient.write(buffer, 0, bytesRead);
                finally {
                    //toClient.close();
                    fromFile.close();
            } else {
                System.out.println("no files");
        public static void main(String[] args) {
            try {
                new fileTransferSend("test.jpg");
            }catch(Exception e) {e.printStackTrace();}
    I know that the client never reads -1 becuase i doesn�t close the stream.
    Is there anyway to tell the client that the file is downloaded?

    A common (and easy) TCP/IP protocol is to send length, followed by data.
    Because TCP/IP is a stream-oriented protocol, a receiver can never absolutely determine where the first packet ends and the second packet begins. So it is common to send the length of the packet, followed by the packet itself.
    In your case, you could send length of file, followed by file data. It should be fairly easy to obtain file length and send that as a 32-bit (or 64-bit value). Here is an idea (not code) for the receiver:
    receive (4) // where 4 = number bytes to receive
    unsigned length = convert 4 bytes to unsigned integer
    while (length != 0)
    n = receive ( length ) // where n = number bytes actually received, and length = number bytes desired
    Or, you can use the concept of an "Escape" character in the stream. Arbitrarily choose an ESCAPE character of 0x1B (although it could be any 8-bit value). When the receiver detects an ESCAPE char, the next character can be either control or data. So for end of file you might send 0x1B 0x00. If the byte to be sent is 0x1B, then send 0x1B 0x1B. The receiver would look something like this:
    b = read one byte from stream
    if (b == 0x1B)
    b = read one byte from stream
    if (b == 0x00) then end of file
    else place b in buffer
    else
    place b in buffer
    Later.

  • Send XML over Sockets

    I am beginning and I need to send XML formatted data from Swing Client to Server for parsing/processing/and response.
    There are no web server available to use. I think its best to use socket connection, but how do I send xml data over socket, and how do I receive it from server and parse it?
    I have read and cannot find a similar example.

    Xerces has DOMSerializer which can be used to serialize a Document object to a string. Once it's a string it's trivial to transmit over a socket connection. On the other side, to parse it, you'll have to create a StringReader for the received string and then an InputSource from the StringReader. You'll then be able to pass the InputSource to the DocumentBuilder.parse( ) method to generate a Document on the receiving side.
    Hope that helps,
    - Jesse

  • Problem with Sending files over Sockets

    Hi. I have a problem when I try to send files over sockets. When I send text files it works well but when I try to send .jpg or other kind of files it doesn't work well because some characters are wrong, I hope you can help me.
    Here is my code:
    //Sender code
    import java.io.*;
    import java.net.*;
    class Servidor{
         Servidor(){
              try{
                   String arch="art.jpg";
                   ServerSocket serv=new ServerSocket(125);
                   Socket socket=serv.accept();
                   System.out.println("Conectado");
                   int c;
                   BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   FileInputStream fis=new FileInputStream(arch);
                   File f=new File(arch);
                   bw.write(""+f.length());
                   bw.newLine();
                   bw.flush();
                   System.out.println("Escribiendo");
                   while((c=fis.read())!=-1){
                        bw.write(c);
                   bw.flush();
                   fis.close();
                   System.out.println("Terminado");
                   while(true){
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Servidor();
    //Client code
    import java.io.*;
    import java.net.*;
    class Cliente{
         Cliente(){
              try{
                   Socket socket=new Socket("localhost",125);
                   System.out.println("Conectado");
                   BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   long tam=Long.parseLong(br.readLine());
                   long act=0;
                   FileOutputStream fos=new FileOutputStream("resp.jpg");
                   System.out.println("Recibiendo: "+tam);
                   while(act<tam){
                        fos.write(br.read());
                        act++;
                   System.out.println("Terminado: "+act+" / "+tam);
                   fos.close();
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Cliente();
    }

    I don't think you want BufferedReader and OutputStreamWriter, you want ByteArrayOutputStream and ByteArrayInputStream . The problem is that you are sending jpegs (binary data) as text.

  • FTP/SFTP/FISH (etc) slow file transfer rate over LAN

    Hi everyone,
    I have a problem with transferring files over my home network that has been bothering me for quite some time.
    I have a 802.11n router which should provide me with the transfer rate up to 150 Mbps (afaik). When I download files from the Internet, 3 MB/s data transfer rate is of no problem.
    However, when receiving or sending data over LAN, the transfer rate is much slower (1.8 MB/s).
    My rough guess is (after reading some papers on this topic) that TCP protocol is causing this (its flow control feature to be exact), since TCP max window size is too small on Linux by default.
    So, setting TCP max window size to a greater number should solve this.
    I tried putting this:
    # increase TCP max buffer size setable using setsockopt()
    # 16 MB with a few parallel streams is recommended for most 10G paths
    # 32 MB might be needed for some very long end-to-end 10G or 40G paths
    net.core.rmem_max = 16777216
    net.core.wmem_max = 16777216
    # increase Linux autotuning TCP buffer limits
    # min, default, and max number of bytes to use
    # (only change the 3rd value, and make it 16 MB or more)
    net.ipv4.tcp_rmem = 4096 87380 16777216
    net.ipv4.tcp_wmem = 4096 65536 16777216
    # recommended to increase this for 10G NICS
    net.core.netdev_max_backlog = 30000
    # these should be the default, but just to be sure
    net.ipv4.tcp_timestamps = 1
    net.ipv4.tcp_sack = 1
    in /etc/sysctl.conf but to no avail.
    So either there is no problem with the max window size setting, or the Linux kernel ignores it (maybe because /proc is no longer supported?).
    Thanks for any neat ideas.
    Last edited by Vena (2012-06-01 21:48:14)

    Bump? No ideas whatsoever?

  • Memory Leak in TCL UDP socket

    Hi all,
    I am currently looking at a memory leak issue in the TCL UDP socket configuration when the fconfigure command is issued under a procedure.
    Under a normal scenario where the socket is configured globally, the system handles the memory well and we do not see an increase.
    The folowing examples are not the actual code implemented but provide an example of the condition under which the leak is seen.
    set msg [udp_open]
    fconfigure $msg -blocking false -buffering none -translation binary -remote [list 10.70.0.112 1234]
    proc send {} {
        global msg
        puts -nonewline $msg "HELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLO"
        return
    set done 0
    while {($done <= 1000)} {
        set done [expr {$done + 1}]
        after 250
        send
    If we wish do dynamically modify the parameters of the socket, we get an ever increasing consumption of memory (show memory dead - decrease in processor free). for example:
    set clients [list]
    lappend clients "10.70.0.111 1234"
    lappend clients "10.70.0.112 1234"
    set msg [udp_open]
    fconfigure $msg -blocking false -buffering none -translation binary
    proc send {} {
        global clients
        global msg
        foreach peer $clients {
            fconfigure $msg -remote $peer
            puts -nonewline $msg "HELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLO"
        return
    set done 0
    while {($done <= 1000)} {
        set done [expr {$done + 1}]
        after 250
        send
    I have tested multiple scenatios using flush, return, closing and opening the socket within the procedure, all to the same result - fconfigure in a procedure creates a memory leak in line with the data rate passing through the socket.
    I am seeing this across multiple device types and IOS (819,5915,5940,2901,2921,3945) 15 series M/T/GC IOS. I guess the question is, is there a problem with the construct of the procedure in which I am missing something on the channel side to release the memory or does this appear to be a bug?
    any help would be appreciated.
    Regards,
    Robert.

    Hi,
    could you please tell me the package version number you are using?
    You can obtain it by calling "package re udp".
    thx

  • Change UDP Socket.ReceiveBufferSize under Windows

    I've previously used a LabVIEW LLB that allows customizing a TCP socket (TCP_NODELAY LLB) to enable and disable delayed acks. This NI LLB contains a pasword protected VI that returns a raw TCP socket ID that is in turn used as an input to a Call Library Function node. A previous post on the NI forums indicates to me that the Windows default buffer size is used (8192 ...
    I would like to increase the Socket.ReceiveBufferSize for a LabVIEW UDP Connection ID.
    MSDN Windows Socket.ReceiveBufferSize property info
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness
    Solved!
    Go to Solution.

    Sorry for the confusing post. I'm using the LabVIEW UDP VIs. My situation is:
    I am running three UDP receivers (Reentrant VI & VI Server) using
    three point-to-point Gigabit Ethernet connections. I drop data when
    sending rates are > 2.4 Mbit/sec. Data is only sent in one
    direction. I have used a TCP version of my application where the CPU
    load is ~ 50%, with (of course) no dropped data because of TCP. I have
    also used TCP_Nodelay.llb to disable nagling, and see 80 to 90% CPU utilization.
    I've simply replaced the TCP Open, Receive and Close functions with UDP
    functions. While running, my CPU load fluctuates from 80 to 100%, and I
    drop data.  UDP has no sequencing or acks to manage, so I can't imagine
    why the CPU load would be higher AND that I would drop data. I've run
    the UDP version at half my goal (1.2 MBit/sec) without dropping data. I
    do use a 1 ms timeout on the UDP and TCP reads.
    I would like to use the same technique to retrieve a UDP raw socket ID, then use that ID to configure SO_RCVBUF instead of TCP_NODELAY to try and eliminate the data loss. I would like to increase the buffer size, or even possibly set it to zero after reading this CodeGuru forum entry.
    Message Edited by Phillip Brooks on 02-28-2007 10:13 AM
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness
    Attachments:
    TCP_NODELAY.llb.gif ‏30 KB

  • Slow send rate with 1K Bytes Message

    I have looked all over the doc and i can't figure out this.
    This is my scenario:
    - Weblogic 10.3.1
    - I have a producer that's sending 1K bytes Messages in a loop
    - Messages are non-persistent
    - I have prefetch and async enabled on the ConnectionFactory I'm using
    - I have quotas disabled
    The issue I'm having is:
    - I can't get more than 24 messages / second on the producer.
    Funny thing is, if I set the message size to 479, the message rates are good. If I set it to 480 I get the 24 messages / second.
    So far this sound like a bug.
    Any help here would be appreciated...
    Follows some code:
    The test I'm doing is pretty simple:
    // Establishing a consumer:
                   InitialContext ctx = new InitialContext(env);
                   ConnectionFactory cf = (ConnectionFactory) ctx.lookup("CF");
                   Connection connRec = cf.createConnection("admin", "my-password");
                   connRec.start();
                   Session sessRec = connRec.createSession(false,
                             Session.AUTO_ACKNOWLEDGE);
                   Destination queue = sessRec.createQueue("./ttt!MyLocalQueue");
                   MessageConsumer consRec = sessRec.createConsumer(queue);
                   boolean useListener = true;
                   consRec.setMessageListener(new MessageListener() {
                        @Override
                        public void onMessage(Message paramMessage) {
                             // do nothing
    // The producer part:
                   Connection conn = cf.createConnection("admin", "my-password");
                   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                   MessageProducer prod = sess.createProducer(queue);
                   prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                   long timeStart = System.currentTimeMillis();
                   for (int iloop = 0; iloop < 10; iloop++) {
                        System.out.println("i = " + iloop);
                        int nmsg = 100;
                        int warmup = 20;
                        for (int i = 0; i < nmsg + warmup; i++) {
                             if (warmup == i) {
                                  timeStart = System.currentTimeMillis();
                             BytesMessage msg = sess.createBytesMessage();
                             msg.writeBytes(new byte[1024]);
                             prod.send(msg);
                        long timeEnd = System.currentTimeMillis();
                        double diff = (timeEnd - timeStart);
                        double timeProd = nmsg * 1000 / diff;
                        System.out.println("produced " + nmsg + " msgs in " + diff
                                  + " with msgs/sec=" + timeProd);
                   conn.close();
    Edited by: user1693918 on Jul 2, 2010 4:20 PM

    24 messages/second is extremely slow.
    Some thoughts:
    * You should see send rates of a few thousand per second if there's no other load on the system, and 10,000s messages second with one-ways (provided you can drain the messages fast enough).
    * To ensure senders don't far outpace consumers, you need some sort of flow control.
    * To reach full performance with JRockit, you may need to send in a tight loop for approx 3 to 5 minutes, and with Sun, you may need to send for at least 30 seconds (JR takes longer to warmup).
    * Most users are far more interested in receives per second than sends per second. Send throughput usually doesn't correlate with consumption rates unless there's some sort of flow control mechanism in the application or the tuning...
    * The System.currentTimeMillis() call on most operating systems and JVMs actually has a 10 millisecond granularity. Since you should likely be able to send a few thousand messages a second in most cases, this granularity is far to coarse if your just sending a few messages between clock checks. You should send at least a few hundred messages between each clock check. In my benchmarking code I tend to use an algorithm like this:
       loop
         perform 100 operations
         if 30 seconds has not passed yet, then continue
         report throughput
         continue  * See [ the JMS Performance and Tuning Check List | http://download.oracle.com/docs/cd/E14571_01/web.1111/e13814/jmstuning.htm#PERFM294 ] for tuning advice.
    Can you repost your test code with the "{code}" tags before and after (place on its own line, and strip off the quotes)? Its a bit hard to read otherwise.
    Regards,
    Tom

Maybe you are looking for

  • How can i view monthly calendar entries in OS7 like in OS6?

    I just purchased an iPhone 5S with OS7;I  had been using a 4S with OS6.  I cannot figure out how to change view of calendar.  On my 4S I could see entries when I looked at the whole month calendar.  On the 5S, I only see a dot for an event; I have to

  • GR quantity zero in Subcontract PO history (SPU problem suspected)

    we are able to successfully generate a Good Receipt for the PO using transaction MB01. the quantity is not subtracting in PO after the GR creation. Regards, Kiran.L

  • Can I install a 200GB HD into my G4 Quicksilver?

    I have a 933MHz G4 Quicksilver with a 60GB PATA drive. I replaced the drive today with a Maxtor 200GB Ultra ATA/133 drive. But my Mac only has Ultra ATA/66 and I am worried that my drive may crash one day because I have exceeded the 128GB limit. But

  • Scroll Bars in IWDWindow

    Hello all,             I hve implemented a custom pop up window using IWDWindow class. Can and how do i implement scroll bars in the same?

  • Read text in pdf files

    Hi Ppl, Is it possible to read text from pdf file ? We can use activex controls to open and display pdf files, but these activex doesn seem to support reading of text from these pdf files. Help me out plz. Thanks