How to make a Simple NIO Scalable Server?

I want to learn NIO for a project, but first want to start out simple. I want to figure out how to send a string across from clients to a server using NIO. I tried looking up stuff, but got caught in the terminology and such. How can I make a simple scalable server (agh tripple S) to send strings across? (like a chat server or something). All I know is I need to use a Selector and some Threaded loops to do stuff.
I found http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf and tweaked the code to make (what I thought was) a simple server, but I do not know how to make client code or even whether or not my Server code works.
This is what I have so far:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.net.*;
import java.util.*;
import static java.lang.System.*;
public class NIOTest {
public static void main(String args[]) throws Throwable
try {
new Thread(new NIOTestServer()).start();
} catch(Exception e) {
e.printStackTrace();       
class NIOTestServer implements Runnable
final Selector selector;
final ServerSocketChannel serverSocket;
int chatPort=9990;
public NIOTestServer() throws Exception
selector=Selector.open();
serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(
new InetSocketAddress(chatPort));
serverSocket.configureBlocking(false);
SelectionKey sk =
serverSocket.register(selector,
SelectionKey.OP_ACCEPT);
sk.attach(new Acceptor());
public void run()
try
while(!Thread.interrupted())
selector.select(); //Blocks until atleast one I/O event has occured
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
while(it.hasNext())
dispatch(it.next());
catch(Throwable lol)
lol.printStackTrace();
void dispatch(SelectionKey k)
Runnable r = (Runnable)(k.attachment());
if (r != null)
r.run();
class Acceptor implements Runnable
{ // inner class to accept the event
public void run()
try
SocketChannel c = serverSocket.accept();
if (c != null)
new Handler(selector, c);
catch(IOException ex) {ex.printStackTrace();}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.net.*;
import java.util.*;
import static java.lang.System.*;
final class Handler implements Runnable {
final SocketChannel socket;
final SelectionKey sk;
ByteBuffer input = ByteBuffer.allocate(1024);
ByteBuffer output = ByteBuffer.allocate(1024);
static final byte READING = 0, SENDING = 1;
byte state = READING;
Handler(Selector sel, SocketChannel c) throws IOException
socket = c; c.configureBlocking(false); //makes it non blocking
// Optionally try first read now
sk = socket.register(sel, 0);
sk.attach(this);
sk.interestOps(SelectionKey.OP_READ);
sel.wakeup();
boolean inputIsComplete()
return input.hasRemaining();
boolean outputIsComplete()
return output.hasRemaining();
void process()
CharBuffer buf=input.asCharBuffer();
buf.flip();
out.println(buf);
public void run()
try {
if (state == READING) read();
else if (state == SENDING) send();
catch (IOException ex) { ex.printStackTrace(); }
void read() throws IOException
socket.read(input);
if (inputIsComplete())
process();
state = SENDING;
// Normally also do first write now
sk.interestOps(SelectionKey.OP_WRITE);
void send() throws IOException
socket.write(output);
if (outputIsComplete()) sk.cancel();
}again this is a rough incomplete code test.

See http://forum.java.sun.com/thread.jspa?forumID=536&threadID=5277053. You can use Telnet as a test client. When you come to write your own client, use java.net, not java.nio.

Similar Messages

  • JDialog Problem: How to make a simple "About" dialog box?

    Hi, anyone can try me out the problem, how to make a simple "About" dialog box? I try to click on the MenuBar item, then request it display a JDialog, how? Following is my example code, what wrong code inside?
    ** Main.java**
    ============================
    publc class Main extends JFrame{
    public Main() {
              super();
              setJMenuBar();
              initialize();
    public void setJMenuBar()
         JMenuBar menubar = new JMenuBar();
            setJMenuBar(menubar);
            JMenu menu1 = new JMenu("File");      
            JMenuItem item = new JMenuItem("About");      
            item.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                  // About about = new About(this);
               // about.show();
            menu1.add(item);
         menubar.add(menu1);
    public static void main(String args[]){
         Main main = new Main();
    }** About.java**
    =============================
    import java.awt.*;
    import javax.swing.*;
    public class About extends JDialog{
         JPanel jp_top, jp_center, jp_bottom;
         public About(JFrame owner){
              super(owner);
              setDefaultCloseOperation( DISPOSE_ON_CLOSE );
              Image img = Toolkit.getDefaultToolkit().getImage(DateChooser.class.getResource("Duke.gif"));          
              setIconImage( img );
              setSize(500,800);
              Container contentPane = getContentPane();
             contentPane.setLayout(new BorderLayout());           
             contentPane.add(getTop(), BorderLayout.NORTH);
              contentPane.add(getCenter(), BorderLayout.CENTER);
              contentPane.add(getBottom(), BorderLayout.SOUTH);
              setResizable(false);
               pack();            
               setVisible(true);
         public JPanel getTop(){
              jp_top = new JPanel();
              return jp_top;
         public JPanel getCenter(){
              jp_center = new JPanel();
              return jp_center;
         public JPanel getBottom(){
              jp_bottom = new JPanel();
              jp_bottom.setLayout(new BoxLayout(jp_bottom, BoxLayout.X_AXIS));
              JButton jb = new JButton("OK");
              jp_bottom.add(jb);
              return jp_bottom;
    }

    Code looks reasonable except
    a) the code in the actionPerformed is commment out
    b) the owner of the dialog should be the frame
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

  • How to make a simple Quiz?

    Could anyone help me with some hints and maybe sample code (or tutorial :)) how to make a simple quiz, with multiple
    answers choices, and a score function.
    //D

    You could for example do it like this:
    import java.io.*;
    class Quiz
    public static void main (String [] args)
    BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
    System.out.println("SUPERQUIZ");
    System.out.println("How many legs does a horse have?");
    System.out.println();
    System.out.println("1");
    System.out.println("2");
    System.out.println("3");
    System.out.println("4");
    int answer = Integer.parseInt(in.readLine());
    if (answer == 4)
    System.out.println("The answer is correct");
    else
    System.out.println("The answer is incorrect");
    This is just a basic program, hope you understand it (hopefully it works).
    �sbj�rn

  • How to make CUCM as a TFTP server , then copy files to Voice Gateway ?

    how to make CUCM as a TFTP server , then copy files to Voice Gateway ? anyone knows?

    Hi,
    Please check the following link
    http://www.cisco.com/c/en/us/td/docs/voice_ip_comm/cucm/admin/6_1_1/ccmsys/cucm-accm-611/a02tftp.html#wp1023004
    Understanding How Devices Access the TFTP Server
    You can enable the IP phones and gateways to discover the TFTP server IP address in one or more of the following ways, depending on the device type:
    •Gateways and phones can use DHCP custom option 150.
    Cisco recommends this method. With this method, you configure the TFTP server IP address as the option value.
    •Gateways and phones can use DHCP option 066.
    You may configure either the host name or IP address of the TFTP server as the option value.
    •Gateways and phones can query CiscoCM1.
    Ensure the Domain Name System (DNS) can resolve this name to the IP address of the TFTP server. Cisco does not recommend this option because it does not scale.
    •You can configure phones with the IP address of the TFTP server. If DHCP is enabled on the phone, you can still configure an alternate TFTP server IP address locally on the phone that will override the TFTP address that was obtained through DHCP.
    •Gateways and phones also accept the DHCP Optional Server Name (sname) parameter.
    •The phone or gateway can use the value of Next-Server in the boot processes (siaddr).
    Devices save the TFTP server address in nonvolatile memory. If one of the preceding methods was available at least once, but is not currently available, the device uses the address that is saved in memory.
    You can configure the TFTP service on the first node or a subsequent node, but usually you should configure it on the first node. For small systems, the TFTP server can coexist with a Cisco Unified Communications Manager on the same server.
    HTH
    Manish

  • How to make a simple Pc Speaker sound output?

    Hello,
    how can a make a simple PC Speaker sound output like the standard beep for errormessages?
    Can anybody help me?
    Thanks,
    Alex

    Use this:Toolkit.getDefaultToolkit().beep(); or this: System.out.print("\0007");
    System.out.flush();

  • How to make a simple C program universal from the command line???

    Hi all,
    I've developed widgets that use a simple C program. I had no clue how to make it universal. Apple documentation is all about big projects to be developed inside Xcode and so on, but I don't understand even the introductory remarks...
    As far as I've read, I have to make a binary for PPC and a binary for i386, and then merge it with lipo. Fine. I get my PPC binary from:
    gcc-4.0 prog.c -o prog_ppc -lm -arch ppc -arch ppc64
    Now, it seems that I have to use:
    gcc-4.0 prog.c -o prog_i386 -lm -arch i386
    The latter command didn't work until I added -L/Developer/SDKs/MacOSX10.4u.sdk/usr/lib/ at the end. With this, it creates a binary file, but with the following message:
    /usr/bin/ld: warning fat file: /usr/lib/system/libmathCommon.A.dylib does not contain an architecture that matches the specified -arch flag: i386 (file ignored)
    and I guess this is quite an issue if I don't have the common math functions, no?...
    Can somebody help me? I googled a lot on this, and found nothing helpful.
    Cédric

    Thanks, it helped me. I googled a bit to build up my Makefile, and this is what I got.
    CC= gcc-4.0
    CFLAGS= -isysroot /Developer/SDKs/MacOSX10.4u.sdk -arch ppc -arch i386
    LDFLAGS= -Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk -lm
    TARGETS= skycalc.fixed.c
    all: $(TARGETS)
    $(CC) $(TARGETS) $(CFLAGS) $(LDFLAGS) -o skycalc_universal
    Thanks again.

  • How to make a simple control value comparison a user event?

    Hey everyone,
    I am trying (with no luck) to figure out how to make an event out of a simple control comparison without having to put the controls inside a while loop to be polled or in the event structure.
    For example; how do I make an event when 'numerical control 1' equals 'numerical control 2'?
    I know that I could have these inside a while loop with the event structure and then wire the comparison to a boolean, then reference the boolean's value change event.  But rather, I would like to create an event for the comparison without the boolean and outside the while loop such that the loop doesn't have to run through the comparison each time, and doesn't have to poll the controls and bool.
    Thanks for the help

    Attached is a simple user event structure that I was thinking about.  Using this you can decouple the control from the comparison, it just works on valye comparisons.  Since it uses the event structure there is no polling and is very CPU friendly.  I have allowedfor the comparison to be linked to the "Value 1:value change event" and the compare button true event.  I hope this is what you were looking at.  Also since it is a user event which is dynamically registered you can register/unregister it at will durring execution making it a flexable event handler.  It might be alittle buggy because I have spent about 3 minutes developing it (particularry when passing values into the event structure there might be a state issue from the data flow so local variables are a better choice)
    Paul
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA
    Attachments:
    CompareEventvi.vi ‏49 KB

  • How to make a simple poll

    hi,all
    I would like to make a simple poll in a page of an application,it only concludes two choices: yes and no.when i press the submit button I can see the percentage displayed as pie chart.how to do this ?any suggestions?

    Hi,
    Step 1: Create Table structure and trigger for Sequence. I have not give code to create Sequence. That you can create with DEMO_POLL_SEQ name
    CREATE TABLE "DEMO_POLL"
    (     "ID_PK" NUMBER,
         "RESULT" NUMBER,
         CONSTRAINT "DEMO_POLL_PK" PRIMARY KEY ("ID_PK") ENABLE
    CREATE OR REPLACE TRIGGER "BI_DEMO_POLL"
    before insert on "DEMO_POLL"
    for each row
    begin
    if :NEW."ID_PK" is null then
    select "DEMO_POLL_SEQ".nextval into :NEW."ID_PK" from dual;
    end if;
    end;
    ALTER TRIGGER "BI_DEMO_POLL" ENABLE;
    Step 2:
    Create a new region on apex type Form with table and select "Result" column and make its type Radiogroup and create static lov
    make sure after you create a region go to branch and put clear cache to the same page. so it clears the page item value.
    Step 3:
    Create another region with chart and paste following SQL query
    SELECT NULL LINK,
    REPLACE(REPLACE(RESULT,1,'YES'),0,'NO') LABEL,
    COUNT(RESULT) VALUE
    FROM DEMO_POLL
    GROUP BY RESULT
    ORDER BY RESULT
    Hope this would workout for you.
    And yes you can add me as in your friend list.
    Thanks,
    Jaydip Bosamiya,
    +91 - 76000 23053
    [http://jbosamiya.blogspot.com|http://jbosamiya.blogspot.com]

  • Hi..I really don't understand how can labview can be a server, can you explain and give me some examples with steps on how to make the labview as a server? Please......

    nn
    Solved!
    Go to Solution.

    erm ok i will explain...
    actually..i know that labview can be a client or server. when the labview be a client, it can access other enable activeX application such as excel or word. i manage to do that a little such as to open excel file and save it at another location by using activeX functions or using the report generation toolkit. yes, i already know and understand the flow or concept of how the labview can be a client. But by using others activeX application especially excel, how can we make the labview be a server? i just need a very easy example and few steps for me to understand how can labview be a server or how excel can control the labview properties?
    really desperate to increase new knowledge.....:-)
    thank you very much for helping me....

  • How to make a simple JPEG flash light to dark on PDF?

    Hello all. Thank you for reading this.
    Please have a look at this online magazine:
    http://viewer.zmags.com/publication/1d272263#/1d272263/1
    Notice how the "Click Here To Read" is flashing?
    Well I'm wondering how do I create that effect? I'm sure it can't be as confusing as I'm trying to learn. Basically I'm creating a online magazine, and I want a JPG/PNG File to flash from dark to light. Is this an effect I add on Adobe InDesign before I convert my (rather large 1,500 page) magazine to a PDF? Or do I open this in Adobe Acrobat X as a PDF and tweak some setting there?
    Or does this file have to be converted to a Shock-wave Flash file? Because I have NO EXPERIENCE in flash files, they seem so confusing.
    Please help if you can!

    Salah Fadlabi wrote:
    Yes that correct
    just export the page logo flashing to (SWF) than place again on indesign document to export with remaining pages to PDF.
    Hello, thank you for your help. When I place the swf file onto the correct InDesign page, I upload it onto the page viewer online, but I see that rather large Flash icon. If you click on the image below you'll be able to see it. I've print screened it.
    ?1
    Am I exporting it incorrectly? I've exported it as a interactive PDF.
    EDIT: I may be confusing you, but this is my general process. I create a magazine. Export it as a PDF, and upload it on a pdf internet viewer called FlipViewer.
    But now, some clients want certain pages/logos etc flashing. So now I need to figure out (for the next magazine that will be uploaded soon), how to make certain logos/badges etc flash. So when I follow your instructions, I upload it as a PDF, then when I open that PDF, I get that flash icon that says "...click to activate", when I click that, then the SWF effects appear over the document. But when I upload that PDF document to FlipViewer, it just appears as a unclickable link. And other magazines that have been uploaded on flipviwer has flashing logos, automatically when you open up the document. What am I doing incorrectly?
    Thank you so much for your help!

  • How to make a simple animation within text area ?

    Hi guys ,I am getting familiar with the Flash animations so I would appreciate a bit of help.
    I am trying to make a simple animation within the text input area i.e.
    1.FAN BASE
    2.FA   NBASE
    What I want is the letter N to move slowly towards letter B.I have done motion tweening but it doesn't work - either the whole text is moving left right  or the letter N is simply skipping to the second position without smooth animation.( there's no error on motion tween by the way) any ideas ?
    Thanks.

    best would be you would create your sentence "fanbase" and break down the single letters into objects by selecting the whole textfield and pressing CTRL+B, convert everyone of them into single movieclips or graphics and tween them accordingly.

  • How to make a simple form layout without ad RAD tool

    I'm trying to make a simple form, but I'm not finding the right layout manager to make the components goes in Y axis. The BoxLayout could solve my problem, if it does not fill all the panel with the components.
    My SCCEE:
    public class TestSimpleForm extends JPanel {
        JLabel nameLbl = new JLabel("Name:");
        JTextField nameField = new JTextField();
        JButton okBtn = new JButton("OK");
        JButton cancelBtn = new JButton("Cancel");
        public TestSimpleForm() {
         add(nameLbl);
         add(nameField);
         add(okBtn);
         add(cancelBtn);
        public static void main(String[] args) {
         JPanel panel = new TestSimpleForm();
         // if i make it a boxlayout panel, the text field size goes huge
    //     panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
         JFrame f = new JFrame();
         f.setContentPane(panel);
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.setSize(400, 600);
         f.setLocationRelativeTo(null);
         f.setVisible(true);
    }

    wellington7 wrote:
    ..My SCCEE:While I don't know what an SCCEE is, I am very familiar with the SSCCE, and..
    public class TestSimpleForm extends JPanel {
    .....this code is surely not an SSCCE.
    Running tool: Java Compile
    /media/disk/projects/numbered/all/TestSimpleForm.java:1: cannot find symbol
    symbol: class JPanel
    public class TestSimpleForm extends JPanel {
                                        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:3: cannot find symbol
    symbol  : class JLabel
    location: class TestSimpleForm
        JLabel nameLbl = new JLabel("Name:");
        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:4: cannot find symbol
    symbol  : class JTextField
    location: class TestSimpleForm
        JTextField nameField = new JTextField();
        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:6: cannot find symbol
    symbol  : class JButton
    location: class TestSimpleForm
        JButton okBtn = new JButton("OK");
        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:7: cannot find symbol
    symbol  : class JButton
    location: class TestSimpleForm
        JButton cancelBtn = new JButton("Cancel");
        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:3: cannot find symbol
    symbol  : class JLabel
    location: class TestSimpleForm
        JLabel nameLbl = new JLabel("Name:");
                             ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:4: cannot find symbol
    symbol  : class JTextField
    location: class TestSimpleForm
        JTextField nameField = new JTextField();
                                   ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:6: cannot find symbol
    symbol  : class JButton
    location: class TestSimpleForm
        JButton okBtn = new JButton("OK");
                            ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:7: cannot find symbol
    symbol  : class JButton
    location: class TestSimpleForm
        JButton cancelBtn = new JButton("Cancel");
                                ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:17: cannot find symbol
    symbol  : class JPanel
    location: class TestSimpleForm
         JPanel panel = new TestSimpleForm();
         ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:22: cannot find symbol
    symbol  : class JFrame
    location: class TestSimpleForm
         JFrame f = new JFrame();
         ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:22: cannot find symbol
    symbol  : class JFrame
    location: class TestSimpleForm
         JFrame f = new JFrame();
                        ^
    /media/disk/projects/numbered/all/TestSimpleForm.java:24: cannot find symbol
    symbol  : variable JFrame
    location: class TestSimpleForm
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                    ^
    13 errors
    Exited: 256

  • How to make a simple 'press  any key...'?

    I need to make a simple statement that will pause the screen, until you hit any key or click the mouse? 'press any key to continue...'
    is there a way to do it without any popup boxes?
    thanks

    System.in.read() will block until a key is hit (unfortunately the enter key counts produces 2 chars on windows...)
    So my suggestion is:
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Press a key to continue....");
    br.readLine();HTH,
    Radish21

  • Please tell me how to use the Simple bluetooth client server example.

    Hi i used the simple bluetooth client server example in labview 7.1. Iam getting an error saying your system does not support the network operation.  I have following doubts also.
    1. Should i pair the device before running the labview.
    2. Should i enable the file transfer wizard in the software given with the bluetooth adapter.
    Please help
    Thank you
    R.Prem kumar 
    09940446193

    Hi R.Prem,
    Could you please let me know what error code is associated with this error message? Also could you please provide a description of the setup you are currently using? Thanks!
    Best regards,
    Steven

  • How to make a simple form made with adobe Muse work with Godaddy server ?

    Hi
    i'm trying to do a little website for my student (excuse my english) and the simple form simply don't work with godaddy server. I put the-email adress and i receive nothing, like nothing happen. I try to place the gdform instead but muse said i can't do that.
    Do yu have a simple explication or a way around that thank you very much
    the site is www.chbh.org
    Josée Bélanger

    Hi
    Please refer to : forums.adobe.com/docs/DOC-3581 to know, how you may have the forms widget provided with Adobe Muse to work with third party hosting.

Maybe you are looking for

  • Save and Exit button

    Hi I want to make a button that commits changes made on the page the button is on and then navigates away to another page. I have tried to set an action on the button matching an action on a page flow. In Internet Explorer it seems to work. The chang

  • Which mobile prepaid plan is best in Australia?

    Hey guys, Okay! So I've always been a iphone user, but I recently bought a BB Bold 9900 because: 1. I heard the battery life is good 2. I like how all your notifications are in one place 3. I just need it to access emails and use wechat and whatsapp.

  • WebServices and Actionscript3.. a few questions

    Hi all, I've set up a small example where I can connect to an .NET Web Service  in Flash using the Flex library mx.rpc.soap.WebService. So it works  fine... I was just wondering if anyone could give me some advice,  information, urls, suggestions or

  • Contact List on Kindle

    Why is my contact list not the same in my Kindle Fire as it is at my office computer?

  • Connecting Discoverer 4i Plus

    Hi there! I have a problem with the Discoverer 4i Plus.... When I try to connect to the Application Server, I received this Connection Error message: "Failed to connect to locator XPTOOracleDiscovererLocator4 pointed by locator.ior file at ...." Can