NIO + multiple packets

How does a web server take multiple packets from a client and make one large request out of it?
I have a NIO server which until now has always assumed "requests" were being sent with one packet. Thus, I built my code to always assume each request = one read from the selection key = one action I take.
For example, if I sent "hello there server" as a command, the server would parse "hello there server" and I would execute some return logic based on that request.
Now I have very long requests that are being received as multiple packets. For example "hello there server blah blah blah" is being recieved as "hello there server" (packet 1) and then "blah blah blah" (packet 2). (just humor me, it happens with longer requests than that ;-)
I assume this happens a lot with http servers - So how do I put multiple packets "together" in NIO? Would I store the contents of each packet into memory until the last packet of a request arrives, then parse the request? Thanks!

If your packets are character strings you can use the fact that CharBuffer implements CharSequence and can be used much like a StringBuffer. See the code example below. Otherwise you could just keep a ByteBuffer and copy the data from using put.
Here's the example for strings, the rest of this application is in my post Taming the NIO Circus
     // reception support
     // receive a string
     private void doRead()
          String dat;
          while(null != (dat = readLine()))client.fromRemote(dat); // send it back to the client
          if(atEof)close();
     private String readLine()
          String s = null;
          fill();
          int len = recvString.length();
          int n = firstNL();
          if(n == -1)
               if(atEof && 0 < len)
                    s = recvString.substring(0);
                    n = len;
          else
               s = recvString.substring(0,n);
               if(len > n+1 && recvString.charAt(n)=='\r' && recvString.charAt(n+1)=='\n')n+=2;
               else n++;
          if(n > 0)
               recvString.delete(0,n);
               recvScanned = 0;
          return s;
     public boolean fill()
          CharBuffer buf;
          int len=0;
          recvBuffer.clear();
          try{len = sch.read(recvBuffer);}
          catch(Exception e){e.printStackTrace();atEof=true;}
          recvBuffer.flip();
          if(len > 0)
               dout(1,"read "+len+" bytes");
               try
                    buf = decoder.decode(recvBuffer);
                    dout(0,"received="+buf);
                    recvString.append(buf);
               catch(Exception e){e.printStackTrace();atEof = true;}
          else if(len < 0)atEof = true;
          return atEof;
     // scan recvString for first new line
     private int firstNL()
          while(recvScanned < recvString.length())
               char ch = recvString.charAt(recvScanned);
               if(ch == '\r' || ch == '\n')return recvScanned;
               recvScanned++;
          return -1;     // no cr or lf
     }

Similar Messages

  • Java NIO - UDP packets

    I'm curious as to the rationale behind having a DatagramPacket class and just using ByteBuffers for TCP connections. I can see the logic, but I'm trying to write a Java framework wrapping NIO with TCP and UDP connections. In my C++ version I have one packet class that I use for both types of connections. I'm stuck with what to implement for Java as I'm going to need two classes, NIO's DatagramPacket and a new TCPPacket. Ideally I would like both to implement an interface or derive from a parent class so I can pass them to all class methods that deal with packets, be they UDP or TCP based. But this won't work. I could wrap DatagramPacket into a new class, and have it and the TCPPacket class implement a Packet interface. But when I'm sending UDP packets I'll be creating two objects for the price of one.
    Any suggestions?
    Thanks

    Remember that in UDP case you can easily lose packets and never know. In TCP you would receive an exception, but UDP can silently discard your packages while in transit.
    My point is, you probably should use a different package class for UDP anyway, maybe adding some stuff like a package ID that would enable re-sending and additional processing in order to ensure a successful communication.
    If you already have this information and some procedures for retrying in your package, then I agree with the previous poster in that you can use bytebuffer for both.

  • Single Serial Packet vs Multiple Packets

    Hello,
    I am trying to program a stepper controller (Anahiem Automation DPE25601) via a usb to serial connector.  Their manual doesn't say how to load a program onto it, so I got a serial port listener used their sample program and found out how to do it myself.  However, it doesn't seem to like sending the entire program in one serial packet, only working when each line is send as seperate packet.  However the data I send is the exact same as their provided sample program.  One thing is that each line is seperated by a carrige return.  Do know why this might be?
    Thanks,
    Eric

    Because that is the way they chose to terminate their commands. If it works when each line has a carriage return then use a carriage return.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • NIO: multiple selectors

    Hi,
    How to implement nb server with multiples selectors? I have 3 selectors and 3 corresponding threads. Every selector serve for one type of operation OP_ACCEPT, OP_READ and OP_WRITE. When I receive a new connection and try to register a new channel with other selector the operation blocks on Channel.register(). It works only with the same selector that accepted this connection.
                        if ( key.isAcceptable() ) {
                            // accepting incoming socket connection
                            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                                 SocketChannel ch = ssc.accept();
                                 // registering client
                                 ch.configureBlocking( false );
                                 ch.socket().setReceiveBufferSize( RECEIVE_BUFFER_SIZE );
                                 ch.socket().setSendBufferSize( SEND_BUFFER_SIZE );
                                 ch.register( readSelector, SelectionKey.OP_READ );
                            }Is it possible to use various selectors?

    Dunno what you've done exactly but Selector.select() does three levels of synchronization which are described in the Javadoc, and SelectableChannel.register() also needs to synchronize on of of those items, i.e. the registered key set.
    A separate reading thread can only help if there are multiple processors and the different threads are executing in different processors. I'm dubious about the strategy of separating reading from writing specifically. If I was going to use multiple selectors I would allocate channels to them arbitrarily rather than on the basis of OP_READ/OP_WRITE.

  • Client management with nio

    Hi everyone!
    I have a program based on nio which has a selector thread that handles the accepts and reads fromt he clients. Another thread, the main one, get's all the read information, handles it and sometimes has to send something back. Now I wonder how I should manage the clients so that I can send something to them based on their ip and what I have to look after to not get into dead locks or similar.
    Thanks for any help in advance!
    Chris

    The select loop in that example I
    posted passes the key to the doRead, doWrite and
    doAccept methods based on what is ready, they do the
    cast.I'm doing it like in your example for reading only. I thought that the trigger for the ON_WRITE select was a call to the write method of a SocketChannel so I tried to do it without the ON_WRITE stuff. Isn't the ON_WRITE select only for safety reasons when write could fail or block? I'm willing to do as you have suggested (with ON_WRITE) but I don't know how to trigger it..
    I have an example of a simple NIO multiple destination
    message switch (a bit like chat) that I will tidy up
    and post. It addresses the issues you are concerned
    with.That sounds awesome. I hope you get it up soon ;)
    Thanks for your help,
    Chris

  • Z data source issue for creating packets

    Hi I have created a Z data source (function module) .
    My issue is I am not able to create data record packets all the data is coming in one packet only.
    The is code is as show below is some one can please assist me how can I change the code so that is can create multiple packets for the option given in Tcode RSA3.
    FUNCTION ZBW_MATERIAL_GROUP_HIE.
    ""Local Interface:
    *" IMPORTING
    *" VALUE(I_REQUNR) TYPE SRSC_S_IF_SIMPLE-REQUNR
    *" VALUE(I_DSOURCE) TYPE SRSC_S_IF_SIMPLE-DSOURCE OPTIONAL
    *" VALUE(I_MAXSIZE) TYPE SRSC_S_IF_SIMPLE-MAXSIZE OPTIONAL
    *" VALUE(I_INITFLAG) TYPE SRSC_S_IF_SIMPLE-INITFLAG OPTIONAL
    *" VALUE(I_READ_ONLY) TYPE SRSC_S_IF_SIMPLE-READONLY OPTIONAL
    *" VALUE(I_REMOTE_CALL) TYPE SBIWA_FLAG DEFAULT SBIWA_C_FLAG_OFF
    *" TABLES
    *" I_T_SELECT TYPE SRSC_S_IF_SIMPLE-T_SELECT OPTIONAL
    *" I_T_FIELDS TYPE SRSC_S_IF_SIMPLE-T_FIELDS OPTIONAL
    *" E_T_DATA STRUCTURE ZBW_MAT_GRP_HIER OPTIONAL
    *" EXCEPTIONS
    *" NO_MORE_DATA
    *" ERROR_PASSED_TO_MESS_HANDLER
    TABLES : /BI0/HMATL_GROUP.
    DATA : BEGIN OF t_hmat OCCURS 0,
    hieid LIKE /BI0/HMATL_GROUP-hieid,
    objvers LIKE /BI0/HMATL_GROUP-objvers,
    iobjnm LIKE /BI0/HMATL_GROUP-iobjnm,
    nodeid LIKE /BI0/HMATL_GROUP-nodeid,
    nodename LIKE /BI0/HMATL_GROUP-nodename,
    tlevel LIKE /BI0/HMATL_GROUP-tlevel,
    parentid LIKE /BI0/HMATL_GROUP-parentid,
    END OF t_hmat.
    DATA : BEGIN OF t_flathier,
    hieid LIKE /BI0/HMATL_GROUP-hieid,
    lv2_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv2_name LIKE /BI0/HMATL_GROUP-nodename,
    lv3_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv3_name LIKE /BI0/HMATL_GROUP-nodename,
    lv4_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv4_name LIKE /BI0/HMATL_GROUP-nodename,
    lv5_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv5_name LIKE /BI0/HMATL_GROUP-nodename,
    lv6_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv6_name LIKE /BI0/HMATL_GROUP-nodename,
    lv7_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv7_name LIKE /BI0/HMATL_GROUP-nodename,
    lv8_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv8_name LIKE /BI0/HMATL_GROUP-nodename,
    lv9_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv9_name LIKE /BI0/HMATL_GROUP-nodename,
    lv10_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv10_name LIKE /BI0/HMATL_GROUP-nodename,
    lv11_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv11_name LIKE /BI0/HMATL_GROUP-nodename,
    material LIKE /BI0/HMATL_GROUP-nodename,
    END OF t_flathier.
    FIELD-SYMBOLS: <f> LIKE LINE OF t_hmat,
    <Level> TYPE ANY.
    data : count(2) type c,
    lv_level(20) type c.
    DATA : lv_count TYPE n.
    DATA : lv_id LIKE /BI0/HMATL_GROUP-nodeid,
    lv_hieid LIKE /BI0/HMATL_GROUP-hieid.
    Auxiliary Selection criteria structure
    DATA: l_s_select TYPE srsc_s_select.
    Maximum number of lines for DB table
    STATICS: s_s_if TYPE srsc_s_if_simple,
    counter
    s_counter_datapakid LIKE sy-tabix,
    cursor
    s_cursor TYPE cursor.
    Select ranges
    RANGES: l_r_nodename FOR /BI0/HMATL_GROUP-nodename,
    l_r_hieid FOR /BI0/HMATL_GROUP-hieid.
    Initialization mode (first call by SAPI) or data transfer mode
    (following calls) ?
    IF i_initflag = sbiwa_c_flag_on.
    Initialization: check input parameters
    buffer input parameters
    prepare data selection
    Check DataSource validity
    CASE i_dsource.
    WHEN 'ZMATERIAL_GROUP_HIE'.
    WHEN OTHERS.
    IF 1 = 2. MESSAGE e009(r3). ENDIF.
    this is a typical log call. Please write every error message like this
    log_write 'E' "message type
    'R3' "message class
    '009' "message number
    i_dsource "message variable 1
    ' '. "message variable 2
    RAISE error_passed_to_mess_handler.
    ENDCASE.
    APPEND LINES OF i_t_select TO s_s_if-t_select.
    Fill parameter buffer for data extraction calls
    s_s_if-requnr = i_requnr.
    s_s_if-dsource = i_dsource.
    s_s_if-maxsize = i_maxsize.
    Fill field list table for an optimized select statement
    (in case that there is no 1:1 relation between InfoSource fields
    and database table fields this may be far from beeing trivial)
    APPEND LINES OF i_t_fields TO s_s_if-t_fields.
    ELSE. "Initialization mode or data extraction ?
    Data transfer: First Call OPEN CURSOR + FETCH
    Following Calls FETCH only
    First data package -> OPEN CURSOR
    IF s_counter_datapakid = 0.
    Fill range tables BW will only pass down simple selection criteria
    of the type SIGN = 'I' and OPTION = 'EQ' or OPTION = 'BT'.
    LOOP AT s_s_if-t_select INTO l_s_select WHERE fieldnm = '0MATERIAL'.
    MOVE-CORRESPONDING l_s_select TO l_r_nodename.
    APPEND l_r_nodename.
    ENDLOOP.
    LOOP AT s_s_if-t_select INTO l_s_select WHERE fieldnm = 'HIEID'.
    MOVE-CORRESPONDING l_s_select TO l_r_hieid.
    APPEND l_r_hieid.
    ENDLOOP.
    Get the data from Hierarchy table
    SELECT * FROM /BI0/HMATL_GROUP INTO CORRESPONDING FIELDS OF
    TABLE t_hmat
    WHERE hieid IN l_r_hieid
    AND objvers = 'A' .
    ENDIF.
    loop through all the 0MATERIAL entries to get all the hirarchy levels.
    Start of change.
    LOOP AT t_hmat ASSIGNING <f>
    WHERE iobjnm = '0MATL_GROUP'
    AND nodename IN l_r_nodename.
    LOOP AT t_hmat ASSIGNING <f>
    WHERE nodename IN l_r_nodename.
    End of change
    lv_count = <f>-tlevel.
    "refresh t_flathier.
    CLEAR: t_flathier. ", lv_level, count.
    MOVE :
    <f>-hieid TO lv_hieid ,
    <f>-nodename TO t_flathier-material,
    <f>-parentid TO lv_id.
    if <f>-iobjnm <> '0MATL_GROUP' .
    move <f>-nodename+3 to t_flathier-material .
    else.
    move <f>-nodename to t_flathier-material .
    endif.
    Added for Last level.
    if lv_count = '1' .
    *t_flathier-lv1_name = t_flathier-material .
    elseif lv_count = '2' .
    t_flathier-lv2_name = t_flathier-material .
    elseif lv_count = '3' .
    t_flathier-lv3_name = t_flathier-material .
    elseif lv_count = '4' .
    t_flathier-lv4_name = t_flathier-material .
    elseif lv_count = '5' .
    t_flathier-lv5_name = t_flathier-material .
    elseif lv_count = '6' .
    t_flathier-lv6_name = t_flathier-material .
    elseif lv_count = '7' .
    t_flathier-lv7_name = t_flathier-material .
    elseif lv_count = '8' .
    t_flathier-lv8_name = t_flathier-material .
    elseif lv_count = '9' .
    t_flathier-lv9_name = t_flathier-material .
    elseif lv_count = '10' .
    t_flathier-lv10_name = t_flathier-material .
    endif.
    DO lv_count TIMES .
    lv_count = lv_count - 1.
    IF lv_count = 1.
    EXIT.
    ENDIF.
    READ TABLE t_hmat WITH KEY
    hieid = lv_hieid
    nodeid = lv_id.
    IF sy-subrc = 0.
    CLEAR lv_id.
    CASE lv_count.
    WHEN '11' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv11_name,
    t_hmat-parentid TO lv_id.
    WHEN '10' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv10_name,
    t_hmat-parentid TO lv_id.
    WHEN '9' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv9_name,
    t_hmat-parentid TO lv_id.
    WHEN '8' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv8_name,
    t_hmat-parentid TO lv_id.
    WHEN '7' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv7_name,
    t_hmat-parentid TO lv_id.
    WHEN '6' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv6_name,
    t_hmat-parentid TO lv_id.
    WHEN '5' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv5_name,
    t_hmat-parentid TO lv_id.
    WHEN '4' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv4_name,
    t_hmat-parentid TO lv_id.
    WHEN '3' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv3_name,
    t_hmat-parentid TO lv_id.
    WHEN '2' .
    MOVE : t_hmat-nodename+3 TO t_flathier-lv2_name.
    ENDCASE.
    ENDIF.
    ENDDO.
    Populate data for level 1 (Class Type)
    READ TABLE t_hmat WITH KEY
    hieid = lv_hieid
    tlevel = 1.
    IF sy-subrc = 0.
    CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT'
    EXPORTING
    input = t_hmat-nodename
    IMPORTING
    output = e_t_data-0class_type.
    CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
    EXPORTING
    input = e_t_data-0class_type
    IMPORTING
    output = e_t_data-0class_type.
    ENDIF.
    populate data to extraction structure ( removing prefixe 'class type')
    MOVE : lv_hieid TO e_t_data-hieid,
    t_flathier-lv2_name TO e_t_data-xhier_lv1,
    t_flathier-lv3_name TO e_t_data-xhier_lv2,
    t_flathier-lv4_name TO e_t_data-xhier_lv3,
    t_flathier-lv5_name TO e_t_data-xhier_lv4,
    t_flathier-lv6_name TO e_t_data-xhier_lv5,
    t_flathier-lv7_name TO e_t_data-xhier_lv6,
    t_flathier-lv8_name TO e_t_data-xhier_lv7,
    t_flathier-lv9_name TO e_t_data-xhier_lv8,
    t_flathier-lv10_name TO e_t_data-xhier_lv9,
    t_flathier-lv11_name TO e_t_data-xhie_lv10,
    t_flathier-material TO e_t_data-0MATL_GROUP.
    APPEND e_t_data.
    CLEAR e_t_data.
    ENDLOOP.
    s_counter_datapakid = s_counter_datapakid + 1.
    IF s_counter_datapakid > 1 .
    RAISE no_more_data.
    ENDIF.
    ENDIF. "Initialization mode or data extraction ?
    ENDFUNCTION.
    As now when I run it in Tcode RSA3 it give only one data packet of some 5k to 6k records.
    Thanks in advance for your help.
    Pawan.

    Hi PS,
    Instead of
    SELECT * FROM /BI0/HMATL_GROUP INTO CORRESPONDING FIELDS OF
    TABLE t_hmat
    WHERE hieid IN l_r_hieid
    AND objvers = 'A' .
    code should look like this .
          OPEN CURSOR WITH HOLD S_CURSOR FOR
          SELECT (S_S_IF-T_FIELDS) FROM /BI0/HMATL_GROUP
        FETCH NEXT CURSOR S_CURSOR
                   APPENDING CORRESPONDING FIELDS
                   OF TABLE E_T_DATA
                   PACKAGE SIZE S_S_IF-MAXSIZE.
    For more information refer to sample code of fm "RSAX_BIW_GET_DATA_SIMPLE"
    Hope that helps.
    Regards
    Mr Kapadia
    ***Assigning points is the way to say thanks in SDN.***

  • Java socket not handling the data packets properly

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

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

  • Mail Activity shows multiple sends for 1 send

    Just a curious little bug. When I send one email, the Mail Activity panel at lower left shows anywhere from 2 to 6 emails being sent. It should show 1. Has anyone else seen this?

    Try not to worry to much about that. Remember, depending on the type of network connection you have, the email client, and the size of the file, the email will not always be sent in one heap.. instead the mail program and the email host and he various servers it may go through to get the infomation to where it needs to it will chunk the infomation into multiple packets, and it will go through multiple servers before it gets to its destination. I would sugest syncronyzing your accuonts, and f you need to rebuild your inbox. But try not to worry about that to much that it shows seveal times in your activity monitor.

  • NAM2 duplicate packets...?

    Hi, I am running NAM2 & NAM2-250S in our 6500 chassis running sup720-3CXL w/ SXI4 code. I am confused by the captures I am pulling down, as there seems to be a ton of multiple packets. At first I thought this was caused by selecting "Both" under data source &  "Both directions" under the actual capture session, but I have tried using one-way data sources combined with one-way capture sessions, but I still seem to be receiving duplicate packets. Any ideas?

    After upgrading the firmware please reset the router and reconfigure it .
     Reset the router
    1. Press and hold the reset button for 30 seconds.
    2. Then, unplug the power keep holding down the reset button for
    another 30 Seconds.
    3. Plug back the power back in, and keep holding down the reset button
    for 30 Seconds.
    4. Release the reset button.

  • Need Help with Packet Loss and routing Loop perhaps???

    Hi,
    I am running into a very odd situation. One of our highly critical systems (172.18.1.2/16) is losing connection intermittently for brief periods of time (1minute, 3 minute, 50 seconds and so on).
    I have gathered some information that I would like to share with you guys:
    The switch is a 3560 (Show version is in ShowVersion.txt)
    default gateway is 172.18.10.254/16 (virtual IP in an HSRP , packet capture is done on the active node)
    I have noticed that pings to one of the default gateways drop infrequently (more frequently from machines on 172.18.0.0/16) segment.
    total number of machines on 172.18.0.0/16 do not exceed 200
    I have captured packets on Interface Vlan1 and I found something very weird, perhaps pointing to a routing loop??? (see capture.png) The ICMP request comes and hits the 172.18.10.254 with TTL of 128 TWICE! then packet capture shows that same packet with TTL decremented by one TWICE! again and again until it reaches TTL of 1 and then it responds with a reply.
    At times it completely ignores the requests and causes a request timed out.
    I am confused and need help in right direction. I really appreciate it.
    can you also confirm if the multiple packets mean routing loop somewhere?
    Thanks

    Could you post a copy of your HRSP config and the results of a #show standby?
    Thanks

  • Datagram Packets sending too fast?

    I am testing sending UDP packets as fast as possible over a 10/100 switch. It seems my problem is actually sending to fast because when I insert a wait (1ms works) into the send routine all the packets are received. When I do not wait I seem to lose about 1%-5% of 20,000 1kB packets (during testing). It seems hard for me to believe the receive routine is doing too much work to cause packet loss because all it is doing is adding the packet to a Queue (which is really a LinkedList). Any comments on this would be very helpful. Some of my code is below:
    The send routine:
    public void sendAll()
    // While still packets in send Queue
    while(!sendQueue.empty())
    // A 1ms wait here works
    send((DatagramPacket)sendQueue.dequeue());
    The receive routine (in the run method of a Thread):
    // Create a datagram socket, bound to the specific port 2000
    DatagramSocket socket = new DatagramSocket(2000);
    boolean f = false;
    while(!f)
    // Create a datagram packet, containing a maximum buffer of 1048 bytes
         DatagramPacket packet = new DatagramPacket( new byte[1048], 1048 );
    // Receive a packet - remember by default this is a blocking operation
    socket.receive(packet);
    // Add the received packet to the receive Queue
    // This routine also checks the first byte of the packet's data to determine packet type
    addToReceiveQueue(packet);
    P.S. The program now does not do anything about packet loss, I will be adding some flow contol soon. If anyone knows some good links to implementation concerning sliding window/flow control for UDP a link would be great. And oh ya, I am required to use UDP - no TCP for me :)

    use setReceiveBufferSize to sets the SO_RCVBUF option to the specified value for the DatagramSocket. The SO_RCVBUF option is used by the the network implementation as a hint to size the underlying network I/O buffers.
    Increasing SO_RCVBUF may allow the network implementation to buffer multiple packets when packets arrive faster than are being received using #receive().

  • Send tcp using thread

    MyRcon2.java
    package rconed;
    import rconed.Rcon;
    import rconed.SourceRcon;
    public void run() {
        try {
          String stringShow = null;
          SourceRcon R = new SourceRcon();
          stringShow = R.send(this.ip, this.port, this.password, this.command);
          System.out.println(stringShow);
        }catch (Exception e) {}
    public void startServer(int portNumber)
        try
          byte[] buf = new byte[1000];
          DatagramSocket ss = new DatagramSocket(portNumber);
          while (true)
            DatagramPacket ip = new DatagramPacket(buf, buf.length);
            ss.receive(ip);
            String rev=new String(buf,0,ip.getLength());
            StringTokenizer st = new StringTokenizer(rev, "/****/");
            MyRcon2 Send = new MyRcon2();
            Send.ip = st.nextToken();
            Send.port = Integer.parseInt(st.nextToken());
            Send.password = st.nextToken();
            Send.command = st.nextToken();
            Thread t =new Thread(Send);
                                                                     t.start();
        }catch (IOException e){}
      }SourceRcon.java
    package rconed;
    import rconed.exception.BadRcon;
    import rconed.exception.ResponseEmpty;
    import java.io.*;
    import java.net.*;
    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    * User: oscahie (aka PiTaGoRaS)<br/>
    * Date: 03-jan-2005<br/>
    * Time: 19:11:40<br/>
    * version: 0.4<br/>
    * Rcon library for Source Engine based games<br/>
    public class SourceRcon {
        final static int SERVERDATA_EXECCOMMAND = 2;
        final static int SERVERDATA_AUTH = 3;
        final static int SERVERDATA_RESPONSE_VALUE = 0;
        final static int SERVERDATA_AUTH_RESPONSE = 2;
        final static int RESPONSE_TIMEOUT = 2000;
        final static int MULTIPLE_PACKETS_TIMEOUT = 300;
        static Socket rconSocket = null;
        static InputStream in = null;
        static OutputStream out = null;
         * Send the RCON command to the game server (must have been previously authed with the correct rcon_password)
         * @param ipStr     The IP (as a String) of the machine where the RCON command will go.
         * @param port      The port of the machine where the RCON command will go.
         * @param password  The RCON password.
         * @param command   The RCON command (without the rcon prefix).
         * @return The reponse text from the server after trying the RCON command.
         * @throws SocketTimeoutException when there is any problem communicating with the server.
        public static String send(String ipStr, int port, String password, String command) throws SocketTimeoutException, BadRcon, ResponseEmpty {
            return send(ipStr, port, password, command, 0);
         * Send the RCON command to the game server (must have been previously authed with the correct rcon_password)
         * @param ipStr     The IP (as a String) of the machine where the RCON command will go.
         * @param port      The port of the machine where the RCON command will go.
         * @param password  The RCON password.
         * @param command   The RCON command (without the rcon prefix).
         * @param localPort The port of the local machine to use for sending out the RCON request.
         * @return The reponse text from the server after trying the RCON command.
         * @throws SocketTimeoutException when there is any problem communicating with the server.
        public static String send(String ipStr, int port, String password, String command, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty {
            String response = "";
            try {
                rconSocket = new Socket();
                InetAddress addr = InetAddress.getLocalHost();
                byte[] ipAddr = addr.getAddress();
                InetAddress inetLocal = InetAddress.getByAddress(ipAddr);
                rconSocket.bind(new InetSocketAddress(inetLocal, localPort));
                rconSocket.connect(new InetSocketAddress(ipStr, port), 1000);
                out = rconSocket.getOutputStream();
                in = rconSocket.getInputStream();
                rconSocket.setSoTimeout(RESPONSE_TIMEOUT);
                if (rcon_auth(password)) {
                    // We are now authed
                    ByteBuffer[] resp = sendCommand(command);
                    // Close socket handlers, we don't need them more
                    out.close(); in.close(); rconSocket.close();
                    if (resp != null) {
                        response = assemblePackets(resp);
                        if (response.length() == 0) {
                            throw new ResponseEmpty();
                else {
                    throw new BadRcon();
            } catch (SocketTimeoutException timeout) {
                throw timeout;
            } catch (UnknownHostException e) {
                System.err.println("UnknownHostException: " + e.getCause());
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection: "+ e.getCause());
            return response;
        private static ByteBuffer[] sendCommand(String command) throws SocketTimeoutException {
            byte[] request = contructPacket(2, SERVERDATA_EXECCOMMAND, command);
            ByteBuffer[] resp = new ByteBuffer[128];
            int i = 0;
            try {
                out.write(request);
                resp[i] = receivePacket();  // First and maybe the unique response packet
                try {
                    // We don't know how many packets will return in response, so we'll
                    // read() the socket until TimeoutException occurs.
                    rconSocket.setSoTimeout(MULTIPLE_PACKETS_TIMEOUT);
                    while (true) {
                        resp[++i] = receivePacket();
                } catch (SocketTimeoutException e) {
                    // No more packets in the response, go on
                    return resp;
            } catch (SocketTimeoutException timeout) {
                // Timeout while connecting to the server
                throw timeout;
            } catch (Exception e2) {
                System.err.println("I/O error on socket\n");
            return null;
        private static byte[] contructPacket(int id, int cmdtype, String s1) {
            ByteBuffer p = ByteBuffer.allocate(s1.length() + 16);
            p.order(ByteOrder.LITTLE_ENDIAN);
            // length of the packet
            p.putInt(s1.length() + 12);
            // request id
            p.putInt(id);
            // type of command
            p.putInt(cmdtype);
            // the command itself
            p.put(s1.getBytes());
            // two null bytes at the end
            p.put((byte) 0x00);
            p.put((byte) 0x00);
            // null string2 (see Source protocol)
            p.put((byte) 0x00);
            p.put((byte) 0x00);
            return p.array();
        private static ByteBuffer receivePacket() throws Exception {
            ByteBuffer p = ByteBuffer.allocate(4120);
            p.order(ByteOrder.LITTLE_ENDIAN);
            byte[] length = new byte[4];
            if (in.read(length, 0, 4) == 4) {
                // Now we've the length of the packet, let's go read the bytes
                p.put(length);
                int i = 0;
                while (i < p.getInt(0)) {
                    p.put((byte) in.read());
                    i++;
                return p;
            else {
                return null;
        private static String assemblePackets(ByteBuffer[] packets) {
        // Return the text from all the response packets together
            String response = "";
            for (int i = 0; i < packets.length; i++) {
                if (packets[i] != null) {
                    response = response.concat(new String(packets.array(), 12, packets[i].position()-14));
    return response;
    private static boolean rcon_auth(String rcon_password) throws SocketTimeoutException {
    byte[] authRequest = contructPacket(1337, SERVERDATA_AUTH, rcon_password);
    ByteBuffer response = ByteBuffer.allocate(64);
    try {
    out.write(authRequest);
    response = receivePacket(); // junk response packet
    response = receivePacket();
    // Lets see if the received request_id is leet enougth ;)
    if ((response.getInt(4) == 1337) && (response.getInt(8) == SERVERDATA_AUTH_RESPONSE)) {
    return true;
    } catch (SocketTimeoutException timeout) {
    throw timeout;
    } catch (Exception e) {
    System.err.println("I/O error on socket\n");
    return false;
    }Rcon.java package rconed;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketTimeoutException;
    import rconed.exception.BadRcon;
    import rconed.exception.ResponseEmpty;
    * Rcon is a simple Java library for issuing RCON commands to game servers.
    * <p/>
    * This has currently only been used with HalfLife based servers.
    * <p/>
    * Example:
    * <p/>
    * response = Rcon.send(27778, "127.0.0.1", 27015, rconPassword, "log on");
    * <p/>
    * PiTaGoRas - 21/12/2004<br>
    * Now also supports responses divided into multiple packets, bad rcon password
    * detection and other minor fixes/improvements.
    * <p/>
    * @author DeadEd
    * @version 1.1
    public abstract class Rcon {
    private static final int RESPONSE_TIMEOUT = 2000;
    private static final int MULTIPLE_PACKETS_TIMEOUT = 300;
    * Send the RCON request. Sends the command to the game server. A port
    * (localPort must be opened to send the command through.
    * @param localPort The port on the local machine where the RCON request can be made from.
    * @param ipStr The IP (as a String) of the machine where the RCON command will go.
    * @param port The port of the machine where the RCON command will go.
    * @param password The RCON password.
    * @param command The RCON command (without the rcon prefix).
    * @return The reponse text from the server after trying the RCON command.
    * @throws SocketTimeoutException when there is any problem communicating with the server.
    public static String send(int localPort, String ipStr, int port, String password, String command)
    throws SocketTimeoutException, BadRcon, ResponseEmpty {
    RconPacket[] requested = sendRequest(localPort, ipStr, port, password, command);
    String response = assemblePacket(requested);
    if (response.matches("Bad rcon_password.\n")) {
    throw new BadRcon();
    if (response.length() == 0) {
    throw new ResponseEmpty();
    return response;
    private static DatagramPacket getDatagramPacket(String request, InetAddress inet, int port) {
    byte first = -1;
    byte last = 0;
    byte[] buffer = request.getBytes();
    byte[] commandBytes = new byte[buffer.length + 5];
    commandBytes[0] = first;
    commandBytes[1] = first;
    commandBytes[2] = first;
    commandBytes[3] = first;
    for (int i = 0; i < buffer.length; i++) {
    commandBytes[i + 4] = buffer[i];
    commandBytes[buffer.length + 4] = last;
    return new DatagramPacket(commandBytes, commandBytes.length, inet, port);
    private static RconPacket[] sendRequest(int localPort, String ipStr, int port, String password,
    String command) throws SocketTimeoutException {
    DatagramSocket socket = null;
    RconPacket[] resp = new RconPacket[128];
    try {
    socket = new DatagramSocket(localPort);
    int packetSize = 1400;
    InetAddress address = InetAddress.getByName(ipStr);
    byte[] ip = address.getAddress();
    InetAddress inet = InetAddress.getByAddress(ip);
    String msg = "challenge rcon\n";
    DatagramPacket out = getDatagramPacket(msg, inet, port);
    socket.send(out);
    // get the challenge
    byte[] data = new byte[packetSize];
    DatagramPacket inPacket = new DatagramPacket(data, packetSize);
    socket.setSoTimeout(RESPONSE_TIMEOUT);
    socket.receive(inPacket);
    // compose the final command and send to the server
    String challenge = parseResponse(inPacket.getData());
    String challengeNumber = challenge.substring(challenge.indexOf("rcon") + 5).trim();
    String commandStr = "rcon " + challengeNumber + " \"" + password + "\" " + command;
    DatagramPacket out2 = getDatagramPacket(commandStr, inet, port);
    socket.send(out2);
    // get the response
    byte[] data2 = new byte[packetSize];
    DatagramPacket inPacket2 = new DatagramPacket(data2, packetSize);
    socket.setSoTimeout(RESPONSE_TIMEOUT);
    socket.receive(inPacket2);
    resp[0] = new RconPacket(inPacket2);
    try {
    // Wait for a possible multiple packets response
    socket.setSoTimeout(MULTIPLE_PACKETS_TIMEOUT);
    int i = 1;
    while (true) {
    socket.receive(inPacket2);
    resp[i++] = new RconPacket(inPacket2);
    } catch (SocketTimeoutException sex) {
    // Server didn't send more packets
    } catch (SocketTimeoutException sex) {
    throw sex;
    } catch (IOException ex) {
    ex.printStackTrace();
    } finally {
    if (socket != null) {
    socket.close();
    return resp;
    private static String parseResponse(byte[] buf) {
    String retVal = "";
    if (buf[0] != -1 || buf[1] != -1 || buf[2] != -1 || buf[3] != -1) {
    retVal = "ERROR";
    } else {
    int off = 5;
    StringBuffer challenge = new StringBuffer(20);
    while (buf[off] != 0) {
    challenge.append((char) (buf[off++] & 255));
    retVal = challenge.toString();
    return retVal;
    private static String assemblePacket(RconPacket[] respPacket) {
    String resp = "";
    // TODO: inspect the headers to decide the correct order
    for (int i = 0; i < respPacket.length; i++) {
    if (respPacket[i] != null) {
    resp = resp.concat(respPacket[i].data);
    return resp;
    class RconPacket {
    * ASCII representation of the full packet received (header included)
    public String ascii = "";
    * The data included in the packet, header removed
    public String data = "";
    * The full packet received (header included) in bytes
    public byte[] bytes = new byte[1400];
    * Length of the packet
    public int length = 0;
    * Represents a rcon response packet from the game server. A response may be split
    * into multiple packets, so an array of RconPackets should be used.
    * @param packet One DatagramPacket returned by the server
    public RconPacket(DatagramPacket packet) {
    this.ascii = new String(packet.getData(), 0, packet.getLength());
    this.bytes = ascii.getBytes();
    this.length = packet.getLength();
    // Now we remove the headers from the packet to have just the text
    if (bytes[0] == -2) {
    // this response comes divided into two packets
    if (bytes[13] == 108) {
    this.data = new String(packet.getData(), 14, packet.getLength() - 16);
    } else {
    this.data = new String(packet.getData(), 11, packet.getLength() - 13);
    } else {
    // Single packet
    this.data = new String(packet.getData(), 5, packet.getLength() - 7);
    MyRcon2.java receive command is
    127.0.0.1/****/54321/****/password****/command"
    if there are more than 1 commands receive at the same time,
    SourceRcon.java line 96 will get error
    "Couldn't get I/O for the connection: null"
    if i change  line 96 to
    System.err.println("Couldn't get I/O for the connection: "+ e.getMessage());
    it display
    Couldn't get I/O for the connection: Invalid argument: JVM_Bind                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

    InetAddress addr = InetAddress.getLocalHost();
    byte[] ipAddr = addr.getAddress();
    InetAddress inetLocal = InetAddress.getByAddress(ipAddr);
    rconSocket.bind(new InetSocketAddress(inetLocal, localPort));Remove those four lines, or at least save yourself some trouble and set inetLocal to null and localPort to zero.
    Why do you want to specify a local bind-address and port? It's not usually done.

  • Container Manager and firewall

    There doesn't appear to be any documentation on this aspect of SCM so I'm hoping somone here will be able to help.
    Essentially, I have two servers separated by a firewall. The usual SunMC ports are accessible between server and agent,
    but unless the firewall rules are dropped I'm unable to create/copy zones in container manager.
    Looking at the firewall logs, a number of server ports are accessed from the agent machine via UDP - one in the 10000
    range and multiple packets to the 8900 range. Does anyone have a defacto list?

    I responded earlier today to your question about malware. I have no idea why the host chose to delete it, but if you will come to the ClamXav Forum I can help you there. Please start with the following detailed information concerning what was found:
    To get detailed infomation on what ClamXav has found, click in the top pane of the ClamXav window showing the Infection / File Name / Status to make sure it's in front and type the key combinations command-A, command-C (or choose "Select-All", "Copy" from the "Edit" menu) to copy the information to your clipboard, then come back here and type command-V or choose "Paste" to show us what was found where.

  • Wrt54gs v6, ping timed out

    hi.
    i've bought wrt54gs v6 (upgraded to v1.50.9 firmware) 2 weeks ago and had several problems with it, most of them are solved by now but still 1 left, a very annoying one.
    It occurs every few hours - i cannot open the setup page (or it takes ages to open) nor ping the router (returns 'timed out' info), at the very same time my internet connection seems fine (might be a bit slower, but it can be only impression, i haven't actually checked it), and i can ping other computers in my network. After reseting router everything goes back to normal for another few hours, or few minutes sometimes. I tried nearly everythink to solve it, contacted linksys online support, gone through few forums and didn't succeed to solve it.
    I've got 4 computers in my network (3 wired and 1 wireless), all running win xp, no firewall is installed on my comp.
    Did anyone have similar problem? Is it something wrong with my configuration or can it be the router itself?
    Thanks for help.

    Well I'm not a professional and I don't own the same router as you but it seems to me it's a download issue. Is it possible you have someone sucking the life out of your internet connection?
    I have the exact same issue with a roommate of mine and the reason for the internet being slow and pretty much non-existant is because of BitLord, BitTorrent, UTorrent and any other programs that use multiple ports.
    If the version of WindowsXP they minimized the avalible ports that used to be avalible in Windows2000 and earlier versions. In doing so there are fewer ports and more activity on these ports.
    But in the end if someone is using BitTorrent in your home they are sending out multiple packets and the outside world is sending multiple packets to your door step. Now if you want good download speeds with BitTorrent you have to open the floodgates and allow people to upload from your machine too. That is the beauty of BitTorrent. However, in doing so your router is bottlenecked and hense you have no internet.
    Hope this helps you find your problem.
    -K

  • Persistent TCP socket trouble

    Hello everybody!
    I'm writing a server/client chat app, mostly for fun but I actually have some use for it as well, when it works that is.
    The server part is pretty much complete, written in Python (since it's so easy and fast to write).
    Anyway, since my chat protocol is supposed to use as little bandwidth as possible, I'm aiming for persistant TCP connections. To make that possible, I've implemented an end of message-marker, so that it reads until it finds the marker, and that's the end of the transmission, instead of reading until the socket is closed and a new connection needs to be reestablished all the time.
    My problem is that I have no idea how to implement this in java! Not in python either to be honest, I used the code from here, although with a few slight modifications:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408859
    (the recv_end function)
    For those who don't understand python, it reads 8kB from the socket, checks in the end marker is in there. If not, it checks if the end market got split between multiple packets, and concatenates everything until the original string is restored.
    Now, I need to do this in java (J2ME/MIDP 2.0 to be exact, but if I get some code to work with I'm sure I can make it work).
    I've got this code in my app, that needs to be replaced:
         protected synchronized StringBuffer read ()
              StringBuffer sb = new StringBuffer();
              int i = 0;
              try
                   while (((i = input.read()) != -1))
                        sb.append((char)i);
              catch (Exception e){}
              finally
                   return sb;
         }I'd be glad to post more code or explain more throughly if needed.
    Other ideas might be welcome as well.
    Help would be very appreciated!

    I've solved it, well kinda anyway. :)
    Not the most effective solution, but since I doubt
    that transmissions >1kB will ever be sent/received
    using this program, it doesn't matter that much.
    This is what I did:
         protected StringBuffer read ()
              StringBuffer soFar = new StringBuffer();
    int r = 0;
              while (true)
                   try
                        r = input.read();
                   catch (Exception e)
                        System.out.println(e.toString());
                   if (r != 4)
                        soFar.append((char)r);
                   else
                        return soFar;
    Surely somewhere in that code you will also need
    r++;

Maybe you are looking for

  • Can I config timesten not to hold all data in memory?

    In our production environment we use a server with 32GB memory to run Timesten, but developer machine only have 2GB memory. Now we are going to fix some issue that require duplicate the production data to Developer machine, can we have config timeste

  • Stock allocation

    Sales in my client is segmentised. Say there are 6 segments. It is being divided using sales groups. I want to allocate the monthly production forecast to each sales segment. Hw can it be handled in SAP??????? Eg: Monthly forecast for the month of Ma

  • Streamlining win XP pro for music question

    Hello guys and gals I will soon be buying the EMU 1212M card and I have a spare 160Gb drive which I will partition so my question is as per topic but I would need some links to places that shows you how to streamline or disable the crap in windows th

  • Purchase Order can't captured Internal order from Asset Master

    Hi experts, I am creating a PO to purchase asset and so using the category Asset. In the asset master, I have defined the Internal Order (investment order) number. At the Account Assignment tab, I entered the asset number in the PO and it is supposed

  • Upgrading to iTunes 6

    Just bought an iTunes music card for the first time, and when i attempted to buy a song through the music store, iTunes prompted me to download version 6. I was cautious about this because i wanted to know if upgrading to a new version gets rid of yo