Sockets using NIO

Hi all,
I have a design question regarding socket architecture.
I have written a server where there are certain services running. this is actually a socket server.
Now i am writing a client.
The challenge is the clients are many applets in one jsp page and all of them will essentially use one connection that is established to the server.
So either we can make a basic applet which all others applets extend and use it.
Can someone help with the code in java socket/nio to use and implement this kind of architecture?

If the server uses NIO, there is not requirement for the client to do the same.
Sharing code does not mean they will share the same connection, only that they will do it the same way. I would suggest you get it to work with individual connections and then optimise it to use a single connection.

Similar Messages

  • Concurrent Sockets using NIO

    I am creating a server using the 1.4x jre and NIO everytime I run the server process I max out at 64 concurrent connections. Spawning a new thread does not seem to work. I know other people have conquered this hurdle and I would appreciate any guidance I could get. Thanks in advance.

    I have my environment set up so I can compile and run test programs (when I want ) using beta 1.4.02. This does not seem to solve the problem. The error is caused when after 64 connections have been accepted and you loop back to selector.select().
    The error message is slightly different depending on which tester I am running but it boils down to
    java.io.IOException: The parameter is incorrect
         at sun.nio.ch.PollArrayWrapper.poll0(Native Method)
         at sun.nio.ch.PollArrayWrapper.poll(PollArrayWrapper.java:146)
         at sun.nio.ch.PollSelectorImpl.doSelect(PollSelectorImpl.java:46)
         at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:62)
         at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:67)
         at mindbridge.test.Server4.run(Server4.java:79)
         at java.lang.Thread.run(Thread.java:536)

  • Error when trying to write to a socket using nio

    Hi,
    I am getting this error when trying to write using the new io
    The system detected an invalid pointer address in attempting to use a pointer argument in a call
    can anyone tell me what's wrong ?

    Please post the whole Exception.printStackTrace report. Also a small example that reproduces the problem.

  • Reading Objects using NIO

    I having problems reading an object using NIO APIs. I am end creating an Object and pass it through a socket. When I retrieve the data from the input stream within the socket I initialize a ByteBuffer by allocating a length. The problem is that there is NO way of knowing what to allocate that ByteBuffer when reading in the object. Below is within a method that allows me to read information from the socket.
    //Allocate the length ByteBuffer.
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //Read the data from the SocketChannel....PROBLEM IS WHAT IF I NEED TO DO MULTIPLE READS
    socketChannel.read(buffer);
    ///We will create a byte array from the ByteBuffer.
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client. *********SPECIAL Class that will cast our generic object into a Message Object.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    ----The problem is if I have more data within that Object. I need to re-allocate the ByteBuffer object and read everything on that socket. I tried the following code but I really don't feel it will be optimized the best for performance. I guess my question is that should I even be using NIO in this situation or Blocking IO?
    Again, here is the code that will read multiple data from the socket until it is -1.
    //Here we will read the information we received by first allocating
    //a ByteBuffer object.
    ByteBuffer buffer1 = ByteBuffer.allocate(5);
    ByteBuffer buffer2 = ByteBuffer.allocate(0);
    //We will read the data from this object.
    while ((socketChannel.read(buffer1)) != -1) {
    //We will check the Buffers and then try to recreate a new ByteBuffer that will put the remaining
    //stuff within the buffer. NOT SURE IF THIS IS THE MOST EFFICIENT WAY OF DOING THIS
    //AND ACTUALLY DON'T HAVE THE CODE WORKING CORRECTLY. THIS IS WHERE I
    //NEED HELP ON THE CORRECT WAY TO DO THIS.
         if (buffer1.remaining() < buffer2.remaining()) {
              buffer1.flip();
              buffer2 = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining());
              System.out.println("tmp 2 Remaining : " + buffer2.remaining());
              //tmp.put(buffer2);
              //buffer2 = tmp;
              System.out.println("Buffer 2 Remaining : " + buffer2.remaining());
         buffer2.put(buffer1);
         buffer1.clear();
    //We will create a byte array from the ByteBuffer.                    
    byte[] b = buffer.array();
    //ByteArrayInputStream that we will create and put the byte array in.
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    //ObjectInputStream where we will use the ByteArrayInputStream.
    ObjectInputStream input = new ObjectInputStream(bis);
    //Object that we will read in.
    Object obj = input.readObject();
    //Message that we will end up receiving.     
    Message receivingMsg = null;
    //Once we have our Message we will end up closing the connection.
    bis.close();
    input.close();
    //We will clear the buffer.
    buffer2.clear();
    buffer1.clear();
    //We will cast the object to a message object so
    //that we can end up sending it through the right
    //routine which will allow us to send a response
    //back to the client.
    Message receivedFromClient = (Message) obj;
    //we will end up taking that message and returning it.
    Message returningMsg = communicate(receivedFromClient);
    //Here we will end up taking the Message and putting it into the ByteBuffer.          
    ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
    socketChannel.write(bb);
    Any help would be greatly appreciated.

    I use my own InputStream class overriding the two standard read functions read( byte[], index, length ) and read(). When you construct it pass in the channel you are reading from and read from the channel on demand. ie when a call to read comes in you read say 100 bytes from the channel. The call required only 80 so these are consumed and the other 20 are buffered. Another read call is made, this time for 50 bytes but we only have 20 buffered so another read of the channel is needed. It is up to you whether you break the contract of read( byte[], index, length ) to keep reading the channel until the full "length" is available, or handle this in your application code.
    Then because this class is InputStream you can wrap it up inside any stream you like such as the ObjectInputStream and the data will be serialized correctly.

  • Using nio And udp

    My first question is. If my server is using nio datagramchanels, my client must use it too?
    can i use traditional datagram socket for comunicate with a nio udp server?
    I have much information on nio and tcp with examples that work. but i can't find examples of communication between client and server using nio UDP. Some page of reference or tutorial?

    My first question is. If my server is using nio
    datagramchanels, my client must use it too?No.
    can i use traditional datagram socket for comunicate
    with a nio udp server?Yes.
    I have much information on nio and tcp with examples
    that work. but i can't find examples of
    communication between client and server using nio
    UDP. Some page of reference or tutorial?You haven't looked very hard. Try 'NIO UDP example' on google.

  • How to write a (g)zip file to disk using NIO

    Hi,
    I want to write some data to a zipped file. I have all data to write to disk in ByteBuffer objects so I want to use NIO. The GZIPOutputstream does not have a getChannel() method. So what is the best method to zip data to file?
    Any comments are welcome!!
    Uli

    Sorry, wrong ByteBuffer in my claspath.
    So why don't you copy the bytes out of it using the get(byte[], int, int) ?

  • Anyone use nio-memory-manager ?? what's it good for?

    Can someone give me an example of when the nio-memory-manager should be used?
    Thanks,
    Andrew

    If I remember the outcome of my experiments with NIO right the situation is as follows:
    1. Allocating/releasing huge shared memory blocks over and over can lead to OS/JVM issues. To avoid this I allocated the max size I wanted from the start (this is an option when configuring "off-heap" storage I believe). When doing it this way I had no reliability issues with the NIO memory manager in my tests.
    2. Tangosol/Oracle used to claim that the off-heap (NIO memory manager) result in worse performance than on-heap - I could not see any clear indication of this but this may be application dependent. For our app the reduced number of JVM:s per server (reducing network communication, number of threads, risk of any JVM performing GC at a given time etc etc) seemed to more than offset the allegedly slower memory manager resulting in MUCH BETTER performance! A lot of queries etc anyhow (at least for us) mainly work against indexes that always are stored "on-heap"...
    3. There is a limitation to 2Gb per NIO block (at least in 32-bit JVM:s not sure about 64:bit - never seen any point in using them since larger heaps than 2Gb seldom work well anyhow and each pointer consumes double the space in heap and CPU-caches) but this is for each CACHE and separate for PRIMARY and BACKUP I believe! So my understanding is that if you (using 64-bit OS) for instance have two (equally big) caches you could allocate max 2 * 2 * 2 = 8Gb of off-heap memory for folding data per JVM (without ANY impact on GC-pauses!) and in addition to that use as much heap as you can get away with (given GC-pause times) for holding the indexes to that data. This would makes a huge difference in JVM count!- for example we today have to run like 10+ JVM:s per server using "on-heap" while we using "off-heap" storage probably could get that down to one or two JVM:s per server!
    4. There may be both OS and JVM parameter that you need to set (depending on OS and JVM used!) in order to allocate large amounts of shared memory using NIO (the default is rather small).
    As for the question about de-allocation I never saw any sign of memory leaks with the NIO memory manager (i.e. space previously occupied by deleted objects were reused for new objects) but as I mentioned above you better allocating the max size NIO memory block you intend to use up-front and that memory will then remain allocated for this use so if your amount of cache data vary and you would like to use memory for other purposes (like heap!) at some point you may be better of sticking with "on-heap" that is more flexible in that respect.
    As I previously mentioned off-heap is today (until Oracle fixes the improvement request!) really only an option if you do not plan to use "overflow protection" or your objects are fixed size :-(
    And if you are interested in using servers with a lot of memory and would like to use "off-heap" please talk to your Oracle sales rep about it! If enough people do that it may allow the Coherence developers to assign more time for making "off-heap" storage better! With this feature in place Coherence will be even more of a "killer application" than it already is!
    Best Regards
    Magnus

  • Can I load batteries from an electrical socket, using the same as my IPhone charger?

    Can I load batteries from an electrical socket, using the same as my IPhone charger?

    Your terminology is confusing...  If you are describing the USB power adapter (that plugs into a wall outlet) that you use to charge your iPhone, you can use the same connection to charge your iPod nano.

  • GZIP using nio ByteBuffer

    In Java 1.4 CharsetEncoder/CharsetDecoder classes were added to encode/decode unicode to/from ByteBuffers to fully utilize the performance advantages of the nio package. Why didn't they do the same for GZIP compresssion/decompression? Does anyone know of a way to read/write a GZIP file using nio and compress/decompress to/from ByteBuffers instead of using GZIPInputStream and GZIPOutputStream?

    llschumacher wrote:
    That will work but it is not what I had in mind. I wish to offload compression/decompression to another thread. Basically what I am doing is reading byte buffers with one thread, queueing them to a second thread to decompress and then queueing the decompressed buffer to a third thread for Unicode Decoding. I also want to use 3 threads in reverse order to perform writes. I can do this with Unicode encode/decode using CharsetEncoder/CharsetDecoder classes because they deal directly with ByteBuffers. Your solution would require me to use the same thread for IO and compress/decompress.here you go...
    1) create a threadpool executor.
    2) inherit from and extend callables to read or write nio channel objects
    3) use Inflate/Deflate on byte[] for your needs.
    4) works for JCE code as well

  • I plug my 1 month old iPad mini retina into a uk plug socket using the out of the box charger, it charged from 0-27% in 3 hours and now refuses to charge at all. Any ideas are more than welcome!!!

    I plugged my iPad Mini Retina in to charge this morning in a UK plug socket using the official out of the box charger.
    It charged from 0-27% in roughly 3 hours.
    I have come home to find it is not charging at all, when turned off when I plug the powered cable in it does turn on as if it is receiving power but it does not charge.
    It is 1 month old and hasn't experienced heavy usage as such.

    Thanks Sig. The information is here: Anything useful stand out?
    Battery Information:
      Model Information:
      Serial Number:    9G1130CJVD3MA
      Manufacturer:    DP
      Device Name:    bq20z451
      Pack Lot Code:    0000
      PCB Lot Code:    0000
      Firmware Version:    0201
      Hardware Revision:    0002
      Cell Revision:    0158
      Charge Information:
      Charge Remaining (mAh):    5663
      Fully Charged:    Yes
      Charging:    No
      Full Charge Capacity (mAh):    5663
      Health Information:
      Cycle Count:    59
      Condition:    Normal
      Battery Installed:    Yes
      Amperage (mA):    261
      Voltage (mV):    12574
    System Power Settings:
      AC Power:
      System Sleep Timer (Minutes):    10
      Disk Sleep Timer (Minutes):    10
      Display Sleep Timer (Minutes):    10
      Wake on AC Change:    No
      Wake on Clamshell Open:    Yes
      Wake on LAN:    Yes
      Current Power Source:    Yes
      Display Sleep Uses Dim:    Yes
      Battery Power:
      System Sleep Timer (Minutes):    10
      Disk Sleep Timer (Minutes):    10
      Display Sleep Timer (Minutes):    2
      Wake on AC Change:    No
      Wake on Clamshell Open:    Yes
      Display Sleep Uses Dim:    Yes
      Reduce Brightness:    Yes
    Hardware Configuration:
      UPS Installed:    No
    AC Charger Information:
      Connected:    Yes
      ID:    0x0100
      Wattage (W):    60
      Revision:    0x0000
      Family:    0x00ba
      Serial Number:    0x00262704
      Charging:    No

  • Why can't GB let me use 'electric guitar' option when using Nio 2/4 interface - I have to use real instrument and miss out on all the effects. Is this normal for all interfaces?

    Why can't GB let me use 'electric guitar' option when using Nio 2/4 interface - I have to use real instrument and miss out on all the effects. Is this normal for all interfaces? The Nio reads hte guitar but GB doesn't....

    Usually effects packages are AU plugins that would have no effect on track selection. Interfaces should have no control over what kind of track you can select. I really think something else is going on her maybe something you overlooked.
    Did you choose the input channel in the track info pane. Try both channel 1 mono or channel 2 mono. Make sure the track is record enabled.

  • Pls, Determine what file's encoding when read a file use NIO

    Hi every body,
    When I use NIO (New I/O JDK1.4) to read a file's content.
    How can I know exactly file's encoding (example: UTF-8, Cp1252, shift-jis ...) to choose right decoder to decode the file??
    Thanks
    Best regards.
    Hung, Nguyen Thanh.

    I think there's no way to do that except...
    If you are sure your files are all in japanese,
    you can use JISAutoDetect encoding.

  • Is is possible to create Socket using Java Stored Procedures/Function(Ora)?

    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?
    OR
    How I can send a message from oracle to Java Desktop Application which is working like server program?
    Please Guide !!

    J3Ganesh wrote:
    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?No, Oracle was very careful to take that feature out of the JDK provided in Oracle 10/11, but you can buy that feature back for, if I remember correctly, about 5000 dollars. (I actually raised a service request on this and then told my rep what I thought about the answer I received--some thing along the line of money grubbing so and so....)
    How I can send a message from oracle to Java Desktop Application which is working like server program?You can make a table and poll it from time to time from the Java side and write and commit what ever you want to the table. I do not know any way to send a signal from Oracle DB an external Java application--Java or PL/SQL stored procedure.

  • Please help: data doesn't get through when using NIO's UDP

    Hi there, I have a 2D client-server game, using NIO's UDP. Whenever the clients send data to server, the data just disappears and not exception nor error appear at the server side.
    Following are the portions of the code where the problem occurs, please help me have a look, many thanks.
    (Please note, I'm using non blocking mode for both client and server, and have no problems with other portions of code, communication was fine, data did get through the network and processed by the server/client. Also, client's DatagramChannel "dChannel" is connected to server, however server's DatagramChannel is not connected to any one).
    //***client's sending code***
    public void sendEventToServer(int[] values) {
        prepWriteBuffer(values);
        try {
          dChannel.write(writeBuffer);
        catch (Exception ioe1) {
          System.out.println("Error when send event to server");
    public void prepWriteBuffer(int[] values) {
        writeBuffer.clear();
        writeBuffer = ByteBuffer.allocate(128);
        if (values[0] == 1) { //fire event
          writeBuffer.putInt(0, firePacketNum);
          firePacketNum++;
        else if (values[0] == 2) { //positional event
          writeBuffer.putInt(0, positionalPacketNum);
          positionalPacketNum++;
        else {
          writeBuffer.putInt(0, -1);
        int j = 4;
        for (int i = 0; i < values.length; i++) {
          writeBuffer.putInt(j, values);
    j += 4;
    writeBuffer.flip();
    //***server's code*****
    public void sReceive(long startTime){
        do {
          readBuffer.clear();   //note, readBuffer is 3072 bytes, bigger than client's sending buffer
          InetSocketAddress sourceAddr = null;
          // read from the channel into our buffer
          try {
                 sourceAddr = (InetSocketAddress) dChannel.receive(readBuffer);
          catch (Exception ioe) {
                 System.out.println(ioe);
          // check for end-of-stream
          //I tried with "if (readBuffer.hasRemaining())", getting the same "data disappearing" problem
          if (sourceAddr == null) {
                 //*********Problem: no matter how often the client is sending, this "if" clause is always entered
                 //that is, data disappeared
                 System.out.println("Server got nothing so breaks.");
                 break;
          else {
                 //******Problem: client keeps sending, but this "else" is never entered.
                 System.out.println("Server now got someting from client.");
                 readBuffer.flip();
                 broadcastEvent(readBuffer, sourceAddr);
        while ((System.currentTimeMillis() - startTime) < 134);

    Here's how the buffer filling stuff works, Ron Hitchen's JAva NIO O'Reilly press, has lots of good diagrams of this.
    buf = ByteBuffer.allocate(10)  // creates new buffer
      0----1----2----3----4----5----6----7----8----9----10
      |    |    |    |    |    |    |    |    |    |    |
      ----------------------------------------+
      ^                                                 ^
      |                                                 |
    position=0                                       limit=capacity
    buf.putInt(5);  // relative put, updates position
      0----1----2----3----4----5----6----7----8----9----10
      | 00 | 00 | 00 | 05 |    |    |    |    |    |    |
      ----------------------------------------+
                          ^                             ^
                          |                             |
                       position=4                    limit=capacity
                       updated
    buf.putInt(4,12);  // absolute put doesn't update position
      0----1----2----3----4----5----6----7----8----9----10
      | 00 | 00 | 00 | 05 | 00 | 00 | 00 | 0c |    |    |
      ----------------------------------------+
                          ^                             ^
                          |                             |
                       position=4                     limit=capacity
    buf.position(8);  // so we set the position ourselves
      0----1----2----3----4----5----6----7----8----9----10
      | 00 | 00 | 00 | 05 | 00 | 00 | 00 | 0c |    |    |
      ----------------------------------------+
                                              ^         ^
                                              |         |
                                         position=8   limit=capacity
    buf.flip();  // flip prepares for write
      0----1----2----3----4----5----6----7----8----9----10
      | 00 | 00 | 00 | 05 | 00 | 00 | 00 | 0c |    |    |
      ----------------------------------------+
      ^                                       ^         ^
      |                                       |         |
    position=0                             limit=8   capacity
    channel.write(buf); // write it out, assume all gets written
      0----1----2----3----4----5----6----7----8----9----10
      | 00 | 00 | 00 | 05 | 00 | 00 | 00 | 0c |    |    |
      ----------------------------------------+
                                              ^         ^
                                              |         |
                                  position=limit=8   capacity
    if it didn't all go out, the position would indicate the
    first unwritten byte.

  • How can I read realtime data from a data socket using DIAdem

    I am currently routing data from an instrument using LabView 7.1 to a data socket. I was trying to figure out how to access that data in real time in DIAdem through the data socket. Another option would be to use the downloaded LabView/DIAdem VI package, but I haven't figured out how to get that to work either, despite the forums here. I would prefer to access it through the data socket, if possible, as the amount of information being transferred is negligable (a string and a double).
    Thank you,
    Sinan Sutcu

    You have to use one of the ScriptDAC blocks. In your case, as you would like to fetch data from a LabVIEW vi, choose the out of the driver input palette. Inside the configuration dialog you can generate a sample script, which is then copied to the windows clipboard. It contains a lot of function prototypes which will be automatically called later during the measurement.
    Basically, the init functions are called during the start of the measurement - here you should connect to the activeX server, the deinit functions are called when stopping the measurement - disconnect from the server here.
    Then there is the function SFD_Readchannel, which is called once for eych tact and each channel you configured. Here, you should exchange the data with your VI.
    I am attatching an example I wrote to control a LabVIEW vi (doing a counter output operation)- that is why the data exchange works the other way around, but I hope it explains the principle.
    Additionally I am adding documentation about the ScriptDAC driver interface.
    Regards
    Ingo Schumacher
    Systems Engineer Sound&VibrationNational Instruments Germany
    Attachments:
    MultiCounterOut.zip ‏995 KB
    Script DAC Driver.zip ‏734 KB

Maybe you are looking for

  • BC is not working for me

         Business catalyst is not working at all. It has been 2 hours! It just continues to load when I try and sign in!

  • Is there a way to see app info after searching for an app by name on the iPad 2?

    I open app store on iPad. Search for an app by name. Results show up. I want to click the app like in iTunes to read the info about it, but the only option is to buy and install it. Shouldn't there be an option to view the info first?

  • What is POP Account option in email settings?

    What is the POP tab for in the email settings?  Mine says this: Existing POP Account List POP Name POP E-Mail Address ActionThere are no POP accounts currently configured.  Add New POP Account

  • JRockit Crashes with empty dump file.

    ---Symptom: JRockit creates an empty dump file and dies without fully starting Dump file looks like this:      [user@computer some_dir]$ cat jrockit.25058.dump      ===== BEGIN DUMP ===============================      [user@computer some_dir]$ ---Ca

  • Playlist - customize columns

    Is there a way to customise columns in a playlist in NokiaOviSuite? I wan to add columns like song playtime, file name (vs. song name), etc. I also want to re-order the columns.