Implement Firewall by using Java

I want to create a firewall(3rd layer) by using Java. Is it possible? Is there any class for these purposes?
I'm not sure if the "DatagramPacket" is the class that I'm looking for.
What is the lower level of network programming which is supported by Java?
Thanks

hm, although i'm not in the "java is too slow" camp i'm still surprised. but then, when using a box as dedicated firewall, java performance is surely good enough.
what made me wonder is that java does not give access to network functionality on a low level which is required for packet filtering. so it would only be feasible to accomplish an application level firewall. i'm no expert at this but i would guess that this kind of firewall has more overhead than a packet filtering firewall.
some research revealed that only the frontend seems to be written in java while the firewall is a configured linux system:
Developed with NetMaster's own Linux distribution tailored specifically for firewall applications, Gateway Guardian is a very flexible, high-end firewall that takes a revolutionary approach to allowing a company to use a lower-end PC as their Internet gateway. Running on a PC that is not the Internet gateway, Gateway Guardian uses a pure Java application to preconfigure hardware, Internet provider settings, and firewall rules through a wizard like format. When the information has been entered, the Java application writes an entire Linux operating system and the custom firewall configuration onto a 3-1/4" floppy diskette.
http://online.securityfocus.com/products/category/134
Gateway Guardian (see Resources) is a one-floppy Linux distribution customized for ipchains-based firewalls. Guardian was developed by NetMaster Solutions and uses a Java GUI application to configure hardware, network settings, and firewall rules through a wizard-like format. When the information has been entered, the Java application writes a Linux image and the custom firewall configuration onto a floppy diskette.
http://www.linuxworld.com/linuxworld/lw-2000-10/lw-10-fwproducts2-p5.html
see here as well:
http://techupdate.zdnet.com/techupdate/stories/main/0,14179,2806287,00.html
any more insights?
robert

Similar Messages

  • How to implement route cipher using java?

    Hi guys,,,
    I really got a headache solving how to implement route cipher using java lang,,i already got the concept but i really dont get how to implement it using java actually i want to make a presentation of how route cipher works using "adobe flash" but first i will implement it using java coz flash actionscripts are closer to java lang.
    Hope you could post some examples or ideas...i would really appreciate it!
    thank you so much...

    just add an action listener (either keypressed or keytyped) to the frame that you want to record. I did this in NetBeans in about 2 seconds. I can simplify it if you need. As for loging it just write the characters to a file output stream.
    public class test extends javax.swing.JFrame {
        /** Creates new form test */
        public test() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyTyped(java.awt.event.KeyEvent evt) {
                    formKeyTyped(evt);
            pack();
        // </editor-fold>
        private void formKeyTyped(java.awt.event.KeyEvent evt) {
            System.out.println(evt.getKeyChar());
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new test().setVisible(true);
        // Variables declaration - do not modify
        // End of variables declaration
    }

  • Trying to implement EAP/TLS using java (as part of RADIUS server)

    Hi
    This is a cross port since I didn't know which forum to post in!
    I'm trying to implement a RADIUS server (EAP/TLS) as part of my master thesis. I'm not used to Java SSL libraries and can't get it to work. The server will respond to an accesspoint that uses 802.1x. I have created certificates using openssl and imported the "cert-clt.pl2"and "root.pem" to a laptop trying to connect to the accesspoint. On the server side i imported the "cacert.pem" and "cert-srv.der" using keytool to a keystore. In my code I read the keystore and create the SSLEngine with following code:
              KeyStore ksKeys = KeyStore.getInstance("JKS");
                ksKeys.load(new FileInputStream("certs/FeebeeCommunity.keystore"), passphrase);
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ksKeys, passphrase);
                KeyStore ksTrust = KeyStore.getInstance("JKS");
                ksTrust.load(new FileInputStream("FeebeeCommunity.keystore"), passphrase);
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(ksKeys);
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                sslEngine = sslContext.createSSLEngine();
                sslEngine.setUseClientMode(false);
                sslEngine.setNeedClientAuth(true);
                sslEngine.setWantClientAuth(true);
                sslEngine.setEnableSessionCreation(true);
                appBuffer = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize());
                appBuffer.clear();
                netBuffer = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
                netBuffer.clear();All I want to do with TLS is a handshake.
    I'm not talking ssl using sockets instead I receive and send all TLS data encapsulated in EAP packet that are incapsulated in RADIUS packets. I start off with sending TLS-Start upon I recive TLS data. I handle it with the following code:
           SSLEngineResult result = null;
            SSLEngineResult.HandshakeStatus hsStatus = null;
            if( internalState != EAPTLSState.Handshaking ) {
                if( internalState == EAPTLSState.None ) {
                    TLSPacket tlsPacket = new TLSPacket( packet.getData() );
                    peerIdentity = tlsPacket.getData();
                    internalState = EAPTLSState.Starting;
                    try {
                        sslEngine.beginHandshake();
                    } catch (SSLException e) {
                        e.printStackTrace();
                    return;
                else if(internalState == EAPTLSState.Starting ) {
                    internalState = EAPTLSState.Handshaking;
                    try {
                        sslEngine.beginHandshake();
                    } catch (SSLException e) {
                        e.printStackTrace();
            TLSPacket tlsPacket = new TLSPacket( packet.getData() );
            netBuffer.put( tlsPacket.getData() );
            netBuffer.flip();
            while(true) {
                hsStatus = sslEngine.getHandshakeStatus();
                if(hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                    Runnable task;
                    while((task=sslEngine.getDelegatedTask()) != null) {
                        new Thread(task).start();
                else if(hsStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
                    try {
                        result = sslEngine.unwrap( netBuffer, appBuffer );
                    } catch (SSLException e) {
                        e.printStackTrace();
                else {
                    return;
            }When I try to send data I use the following code:
               SSLEngineResult.HandshakeStatus hsStatus = null;
                SSLEngineResult result = null;
    //            netBuffer = ByteBuffer.allocate(EAPTLSMethod.BUFFER_SIZE);
                netBuffer.clear();
                while(true) {
                    hsStatus = sslEngine.getHandshakeStatus();
                    if(hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                        Runnable task;
                        while((task=sslEngine.getDelegatedTask()) != null) {
                            new Thread(task).start();
                    else if(hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
                        try {
                            result = sslEngine.wrap( dummyBuffer, netBuffer );
                        } catch (SSLException e) {
                            e.printStackTrace();
                    else {
                        if( result != null && result.getStatus() == SSLEngineResult.Status.OK ) {
                            int size = Math.min(result.bytesProduced(),this.MTU);
                            byte [] tlsData = new byte[size];
                            netBuffer.flip();
                            netBuffer.get(tlsData,0,size);
                            TLSPacket tlsPacket = new TLSPacket((byte)0,tlsData);
                            if( size < result.bytesProduced() ) {
                                tlsPacket.setFlag(TLSFlag.MoreFragments);
                            return new EAPTLSRequestPacket( ID,
                                    (short)(tlsPacket.getData().length + 6),
                                    stateMachine.getCurrentMethod(), tlsPacket );
                        else {
                            return null;
                    }After I sent TLS-Start I receive data and manage to process it but when then trying to produce TLS data I get the following error:
    javax.net.ssl.SSLHandshakeException: no cipher suites in common
    at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Handshaker.java:992)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:459)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1054)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1026)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:411)
    at RadiusServerSimulator.EAPModule.EAPTLSMethod.buildReq(EAPTLSMethod.java:125)
    at RadiusServerSimulator.EAPModule.EAPStateMachine.methodRequest(EAPStateMachine.java:358)
    at RadiusServerSimulator.EAPModule.EAPStateMachine.run(EAPStateMachine.java:262)
    at java.lang.Thread.run(Thread.java:595)
    Caused by: javax.net.ssl.SSLHandshakeException: no cipher suites in common
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1352)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:176)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:164)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:638)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:450)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:178)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Handshaker.java:437)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Handshaker.java:930)
    Any help wold be most greatfull, if any questions or anything unclear plz let me know.
    add some additional information here is a debug output
    Before this I have sent a TLS-star package and this is when I receive new information and then try to create the answer
    [Raw read]: length = 5
    0000: 16 03 01 00 41 ....A
    [Raw read]: length = 65
    0000: 01 00 00 3D 03 01 41 A4 FC 16 A8 14 89 F0 59 81 ...=..A.......Y.
    0010: C8 C9 29 C2 09 D1 0A 70 18 58 DC 2E B0 C8 14 90 ..)....p.X......
    0020: D4 FD A4 C6 32 C9 00 00 16 00 04 00 05 00 0A 00 ....2...........
    0030: 09 00 64 00 62 00 03 00 06 00 13 00 12 00 63 01 ..d.b.........c.
    0040: 00 .
    Thread-2, READ: TLSv1 Handshake, length = 65
    *** ClientHello, TLSv1
    RandomCookie: GMT: 1084488726 bytes = { 168, 20, 137, 240, 89, 129, 200, 201, 4
    1, 194, 9, 209, 10, 112, 24, 88, 220, 46, 176, 200, 20, 144, 212, 253, 164, 198,
    50, 201 }
    Session ID: {}
    Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH
    _3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_RSA_EXPORT1024_WITH_RC4_56_SHA,
    SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EX
    PORT_WITH_RC2_CBC_40_MD5, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_DE
    S_CBC_SHA, SSL_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA]
    Compression Methods: { 0 }
    [read] MD5 and SHA1 hashes: len = 65
    0000: 01 00 00 3D 03 01 41 A4 FC 16 A8 14 89 F0 59 81 ...=..A.......Y.
    0010: C8 C9 29 C2 09 D1 0A 70 18 58 DC 2E B0 C8 14 90 ..)....p.X......
    0020: D4 FD A4 C6 32 C9 00 00 16 00 04 00 05 00 0A 00 ....2...........
    0030: 09 00 64 00 62 00 03 00 06 00 13 00 12 00 63 01 ..d.b.........c.
    0040: 00 .
    Thread-5, fatal error: 40: no cipher suites in common
    javax.net.ssl.SSLHandshakeException: no cipher suites in common
    Thread-5, SEND TLSv1 ALERT: fatal, description = handshake_failure
    Thread-5, WRITE: TLSv1 Alert, length = 2
    Thread-2, fatal: engine already closed. Rethrowing javax.net.ssl.SSLHandshakeEx
    ception: no cipher suites in common
    javax.net.ssl.SSLHandshakeException: no cipher suites in common
    at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Handshaker.java:9
    92)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineI
    mpl.java:459)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(SSLEngineIm
    pl.java:1054)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:10
    26)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:411)
    at RadiusServerSimulator.EAPModule.EAPTLSMethod.buildReq(EAPTLSMethod.ja
    va:153)
    at RadiusServerSimulator.EAPModule.EAPStateMachine.methodRequest(EAPStat
    eMachine.java:358)
    at RadiusServerSimulator.EAPModule.EAPStateMachine.run(EAPStateMachine.j
    ava:262)
    at java.lang.Thread.run(Thread.java:595)
    Caused by: javax.net.ssl.SSLHandshakeException: no cipher suites in common
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1
    352)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:176)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:164)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.chooseCipherSuite(Serve
    rHandshaker.java:638)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.clientHello(ServerHands
    haker.java:450)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.processMessage(ServerHa
    ndshaker.java:178)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:4
    95)
    at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Handshaker.java:437)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Handshaker.
    java:930)
    ... 1 more

    I am developing a simple client/server SSL app using sdk 1.4 (no SSLEngine) and am faced with the same problem. Could anybody track down the problem further?

  • Hiding the Image in another Image using Java

    Hi all,
    I have to implement the Steganography using Java, i have to get two images and have to hide one image in another , please give me some ideas or sample links where i can explore to implement it...
    Thanks & Regards,
    Justin

    Try the ImageConsumer class. The Image's getSource method returns an ImageProducer that can be linked to the consumer.
    Some images (such as BufferedImage) also provides a Raster, which gives access to its contents through a DataBuffer. I don't know which is the easiest way, though...

  • Blocking network packets using java

    Hello Friends,
    I am trying to develop a firewall application using java.I am able to capture packets using third party library called jpcap(from sourceforge).
    Now, the problem is how to block packets.There is no library as such ,to my knowledge atleast,to block network packets.I am finding for a solution
    regards,
    raj

    What do you mean?
    Dropping a TCP/UDP packet would happen at the IP level. Given that TCP/UDP runs on IP (and ICMP as well) that means that basically you must impliment a stack.
    Conversely it might be that the specific stack you are using provides that functionality and you just need to configure it. That would be done via JNI (and has nothing to do with IP/TCP/UDP.)
    If all you are doing is proxying, which is what a firewall does, then you recieve a TCP packet and then just drop it or forward it. Doing that in a Java application however is not actually the same as most firewalls (certainly not dedicated boxes.)

  • Creating Web Services using Java Implementation

    Hi,
    This is quite a general question on how to create a Web Service using Java Implementation that needs to conform to a client XML schema.
    Here are my Version specs,
    I am using Jdeveloper 10.1.3.4.0 and deploying onto OAS 10.1.3.
    I will be creating a J2ee 1.4 (JAX-RPC) Web Service using Document/Wrapped style.
    I have been provided an XML schema from the client which is quite complex.
    Using a top-down approach, I can create my WSDL file and import the XML Schema for my type definitions.
    The Web service aim is to accept some parameters and return some data from the Oracle Database. The
    XML response from the web service must conform to the element, attribute definitions in the provided XML schema.
    From a Java implementation approach, what is the best (simplest or quickest) way to retrieve data from the Oracle
    tables and map each fields/column to the required XML output (defined in the XML schema).
    I'm not too concerned with using Java to retrieve data from the Database, more with how I can map the data returned
    to the required output. Can this mapping task be controlled within the Java program?
    Thanks in advance.

    Hi,
    This is quite a general question on how to create a Web Service using Java Implementation that needs to conform to a client XML schema.
    Here are my Version specs,
    I am using Jdeveloper 10.1.3.4.0 and deploying onto OAS 10.1.3.
    I will be creating a J2ee 1.4 (JAX-RPC) Web Service using Document/Wrapped style.
    I have been provided an XML schema from the client which is quite complex.
    Using a top-down approach, I can create my WSDL file and import the XML Schema for my type definitions.
    The Web service aim is to accept some parameters and return some data from the Oracle Database. The
    XML response from the web service must conform to the element, attribute definitions in the provided XML schema.
    From a Java implementation approach, what is the best (simplest or quickest) way to retrieve data from the Oracle
    tables and map each fields/column to the required XML output (defined in the XML schema).
    I'm not too concerned with using Java to retrieve data from the Database, more with how I can map the data returned
    to the required output. Can this mapping task be controlled within the Java program?
    Thanks in advance.

  • How to use Java NIO to implement disk cache for serialized java objects

    Hi,
    I have a cache (implemented as hahstable etc.) that contains java objects (mostly strings) and swaps objects from runtime memory to the disk and back based on some algorithms. Currently, the reading and writing from the disk is implemented using java.io.* package i.e. fileInputstream and FileOutputStream. Essentially, I serialize the java object and write to the disk and the deserialize and give it back to the Hashtable cache.
    The performance of swapping from disk to memory is kinda slow. I have read that memory mapping would improve the performance.
    My idea is to do the following:
    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBuffer for that but then I have the following questions. I will not store objects in the hashtable anymore.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?
    As you can see, I am beginner in memory mapped io and need help.

    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBufferThis is a good idea, one that I have worked on. It involves quite a bit of manipulation with temporary buffers and a deep working knowledge of object serialization.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?The best way to handle this is do a two-step process, cutting the file into two pieces and gluing it back together where the original one is...
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.It is hard. Wrapping the streams and making the IO work properly is not the challenge however. The hard part comes in hacking the object streams. The object input/output streams use a ClassDescriptor object which only gets written once/ read once. This shouldn't be a problem if you will read/write the entire file at once, but will bring you grief if you want random access to your objects. You will also need an indexing mechanism to support random access.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?I guess it depends on your needs. Do you require random access to objects? NIO provides some performance gains, but mostly for very large amounts of data (>10M in my experience).
    You can always write all your objects into the same file using normal io techniques and you can still generate an index and acheive random access. It might be easier...
    Good luck

  • We have a requirement to print the w2 forms for employees using java application, how can i implement this. Please give some suggestion.

    We have a requirement to print the w2 forms for employees using java application, how can i implement this. Please give some suggestion.

    Anyone any ideas to help please?

  • Implementing n-tier Architecture using java

    Hi !!
    I wish to know how I can proceed to implement n-tier application using java
    or how to implement n-tier application with JBuilder.
    Thanks!

    Easypublic class nTier {
      public static void main(String[] args) {
        int n =5;
        for (int i=0; i<n; i++) {
          System.out.println(i + " tier");
    }Ted.

  • Free source code to firewall using java

    help me to develop a firewall like package as well as web information filter using java code

    If there was a FAQ for this forum question 1 would be as follows.
    Question : How do I build a firewall in Java?
    Answer: You can't. The Java Networking API does not provide the access required to OS networking components neccessary for building a firewall. You will HAVE to use JNI. You should also reconsider your project because Java is not a suitable language for firewall building.

  • Example of using JAVA to implement location transparency

    Dear all,
    Is any example or source code show me how to using JAVA to implement location transparency?
    Thanks
    Ronnie Poon

    <frameset> should not be the child of the <body> element. It should be the child of <html> element.
    This works:
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="1.2" xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:ui="http://www.sun.com/web/ui">
    <jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>
    <f:view>
    <ui:page id="page1">
    <ui:html id="html1">
    <ui:head id="head1">
    <ui:link id="link1" url="/resources/stylesheet.css"/>
    </ui:head>
    <frameset cols="30%,70%">
    <frame name="left" src="faces/Page1.jsp"/>
    <frameset rows="80%,20%">
    <frame name="top" src="faces/rightPage.jsp"/>
    <frame name="bottom" src="faces/bottomPage.jsp"/>
    </frameset>
    </frameset>
    </ui:html>
    </ui:page>
    </f:view>
    <ui:form binding="#{bean.form1}" id="form1"/>
    </jsp:root>
    thanks,
    tsc

  • How advantages of "Call By Reference" can be implemented using Java

    As I know that java doesnot support "Call By Reference" as C++
    does.
    I want to know that how advantages of Call by Reference can be
    implemented using Java.

    There is some misunderstanding here. Method arguments in Java are passed by value. However, if you pass a reference (to an object) by value, you can still modify the object that the (copy of the) reference points to.
    public void method1() {
      StringBuffer buf = new StringBuffer();
      // Here, method2 cannot change the value of the variable buf,
      // but it can modify the object that buf points to.
      method2(buf);
    public void method2(StringBuffer sb) {
      // You can modify the StringBuffer.
      sb.append("hello");
      // But this is useless, it will not change the variable buf
      // in the calling method.
      sb = new StringBuffer();
    }Jesper

  • Resources for implementing HTTP web server using java

    hi ,
    Thanks for giving your precious time in reading the message.I want to build a HTTP web server using java,which will run on my machine and I can communicate with it through web browser(IE) using HTTP requests and response.
    I know java language, but quite new to network programming.I want to gain enough knowledge on network programming in java.Can you please suggest me good books or any other resources available on the internet for the required subject.Any help will be greatly appreciated.
    my email-id is : [email protected]

    hi there my friend,
    I am writing my own web server too. in w3c there is a sample web server called jigsaw-open source :) and simple-
    I do think it worth trying.
    you can contact me if you want to share some source and info. cause I will.
    [email protected]
    but within 2 weeks I will be back for studying for my web server. you have to wait for a while.

  • Implementing partialTriggers  using java code???

    Can we perform Partial Trigger on a component using java code?
    For example,
    I have a textBox component and a commandButton.If bind partialTriggers attribute of the textBox to the commandButton, it gets renedered whenever I click the commandButton.
    Can I acheive the same,by writing some piece of java code inside the action listener of commandButton?
    Regards,
    Lokesh.

    If you bind the component to a bean attribute (i.e. attrXYZ) you can use
    RequestContext.getCurrentInstance().addPartialTarget(attrXYZ);in the listener to update it.
    Timo

  • Socket example using Java 5

    Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
    It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
    //========================== MsgSwitch.java ===========================//
    package pkwnet.msgswitch;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    import java.util.logging.Handler;
    * main class for message switch
    * command line arguments are
    * -p port number for server
    * -s run server
    * -a server ip address including port for client
    * -i idle timer in seconds
    * -n use NIO
    * -c specify connection class
    public class MsgSwitch {
        static private int errors = 0;
        static private String address = "127.0.0.1:6060";
        static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
        static public void main(String [] args) {
            int port = 6060;
            int idleTime = 600;
            boolean server = false;
            boolean nio = false;
            Logger logger = Logger.getLogger("msgswitch");
            for(String arg : args) {
                if(arg.startsWith("-a")) {
                    address = arg.substring(2);
                } else if(arg.startsWith("-p")) {
                    port = argToInt(arg);
                    server = true;
                } else if(arg.startsWith("-i")) {
                    idleTime = argToInt(arg);
                } else if (arg.startsWith("-s")) {
                    server = true;
                } else if (arg.startsWith("-c")) {
                    connectionClass = arg.substring(2);
                } else if (arg.startsWith("-n")) {
                    connectionClass = "pkwnet.msgswitch.NIOConnection";
                } else {
                    String err = "unknown argument=" + arg;
                    logger.severe(err);
                    System.err.println(err);
                    errors++;
            if (errors == 0) {
                if (server) {
                    new Server().listen(port,idleTime, nio);
                } else {
                    new Client().start(address, nio);
            } else {
                fail(errors + " errors encountered", null);
        static private int argToInt(String arg) {
            int val = 0;
            try {
                val = Integer.parseInt(arg.substring(2));
            } catch (NumberFormatException e) {
                String err = "invalid argument format: " + arg;
                Logger.getLogger("msgswitch").severe(err);
                System.err.println(err);
                errors++;
            return val;
        static public void fail(String err, Throwable e) {
            String msg = "Operation terminated: " + err;
            Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
            System.err.println(msg);
            System.exit(12);
        static public Connection getConnection() {
            Connection conn = null;
            try {
                conn = (Connection) Class.forName(connectionClass).newInstance();
            } catch (Exception e) {
                fail ("connection class error", e);
            return conn;
        static public void logCaller(Logger logger, Level level) {
            String text = "CALLED";
            if (logger.isLoggable(level)) {
                try {
                    throw new Exception("logging stack");
                } catch (Exception e) {
                    StackTraceElement [] st = e.getStackTrace();
                    if (st.length > 1) {
                        text += formatElement(st[1]);
                    if (st.length >2) {
                        text += formatElement(st[2]);
                logger.log(level, text);
        static private String formatElement(StackTraceElement ste) {
            return "\n    " + ste.getClassName() + "." + ste.getMethodName()
                + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    //================= Client.java =============================================//
    package pkwnet.msgswitch;
    * a simple Swing chat GUI using Java 5 and sockets.
    * @author PKWooster
    * @version 1.0 August 31,2005
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.SwingUtilities;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import static java.awt.BorderLayout.*;
    client GUI class
    public class Client extends JFrame implements ConnectionListener {
         // swing GUI components
         private JTextField userText = new JTextField(40);
         private JTextArea sessionLog = new JTextArea(24,40);
         private JTextField statusText = new JTextField(40);
         private JPanel outPanel = new JPanel();
         private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem aboutItem = new JMenuItem("About");
         private JMenuItem abortItem = new JMenuItem("Abort");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
         private String address;
        private Connection connection;
        private boolean sendReady = false;
        private boolean nio = false;
         Client() {
        public void start(String address, boolean nio) {
            this.address = address;
            this.nio = nio;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    runClient();
        private void runClient() {   
            connection = MsgSwitch.getConnection();
            connection.addConnectionListener(this);
              buildMenu();
              cp = getContentPane();
              sessionLog.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){userTyped(evt);}
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,NORTH);
              cp.add(sessionLogScroll,CENTER);
              cp.add(statusText,SOUTH);
              setStatus("Closed");
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
              pack();
            setVisible(true);
    * attempt to send the contents of the user text field
        private void userTyped(ActionEvent evt) {
            if (sendReady) {
                String txt = evt.getActionCommand()+"\n";
                userText.setText("");
                toSessionLog("> ", txt);
                sendReady = false;
                connection.send(txt);
    * append text to the session log
         private void toSessionLog(String prefix, String txt) {
              sessionLog.append(prefix + txt);
              sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
    * build the standard menu bar
         private void buildMenu()
              JMenuItem item;
              // file menu
              startItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuStart();}});
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuHost();}});
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuExit();}});
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              helpMenu.add(aboutItem);
              aboutItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuAbout();}});
              menuBar.add(helpMenu);
              setJMenuBar(menuBar);
    * start and stop communications from start menu
         private void mnuStart() {
            if(connection.getState() ==  Connection.State.CLOSED) {
                connection.connect(address);
            } else {
                connection.disconnect();
    *  prompt user for host in form address:port
        private void mnuHost() {
              String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
              if (txt == null)return;
            address = txt;
         private void mnuAbout() {
              JDialog dialog = new JDialog(this, "About Client");
              JTextField text = new JTextField("Simple character client");
            dialog.getContentPane().add(text);
            dialog.pack();
            dialog.setVisible(true);
         // exit menu
         private void mnuExit() {
            exit();
        private void exit() {
              connection.disconnect();
              System.exit(0);
         private void setStatus(String st) {
            statusText.setText(st);
         private void setStatus(Connection.State state) {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
        public void stateChanged(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
        public void dataAvailable(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    String txt = event.getData();
                    if (txt == null) {
                        txt = "$null$";
                    toSessionLog("< ", txt + "\n");   
        public void sendAllowed(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    sendReady = true;
        public void accept(ConnectionEvent event) {
    //========================== Server.java ===============================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    * a simple message switch using stream based socket i/o
    * a very simple text message switching program
    * user commands start with $ and consist of blank seperated arguments
    * other lines sent by the user are forwarded
    * $on nickname targets
    *    sign on as nickname, sending to targets
    * $to targets
    *    change target list, reports current value
    * $list nicknames
    *    list status of specified nicknames
    * $list
    *    list all connected users
    * $off
    *    sign off
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class Server {
        private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
        private Timer idleTimer;
        private Connection conn;
        public void listen(int port, final int idleTime, boolean nio) {
            idleTimer = new Timer();
            idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
            conn = MsgSwitch.getConnection();
            conn.addConnectionListener(new ConnectionListener() {
                public void stateChanged(ConnectionEvent event) {
                public void dataAvailable(ConnectionEvent event) {
                public void sendAllowed(ConnectionEvent event) {
                public void accept(ConnectionEvent event) {
                    Connection uconn = event.getConnection();
                    new User(uconn, perUser, idleTime);
            conn.listen(port);
            idleTimer.cancel();
        private void oneSec() {
            Collection<User> uc = perUser.values();
            for(User u : uc) {
                u.oneSec();
    //================= User.java  ==============================================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * defines the processing for a message switch user
    * @author PKWooster
    * @version 1.0 June 15,2004
    public class User implements ConnectionListener {
        private ConcurrentHashMap<String, User> perUser;
        private String name;
        private String address;
        private boolean signedOn = false;
        private String[] targets;
        private AtomicInteger remainingTime;
        private int idleTime;
        Connection conn;
        Logger logger;
      * construct a user, link it to its connection and put it in the perUser table
        User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
            this.conn = conn;
            logger = Logger.getLogger("msgswitch.user");
            conn.addConnectionListener(this);
            address = conn.getAddress();
            logger.info("creating user " + address);
            perUser = p;
            idleTime = idle;
            remainingTime = new AtomicInteger(idleTime);
            rename(address);
            targets = new String[0];
    * process state changes
        public void stateChanged(ConnectionEvent event) {
            if(event.getState() == Connection.State.CLOSED) {
                close(false);
    * data is available, process commands and forward other data.
        public void dataAvailable(ConnectionEvent event) {
            String msg = event.getData();
            if (msg.startsWith("$")) {
                doCommand(msg);
            } else {
                forward(msg);
            remainingTime.set(idleTime);
    * do nothing for sendAllowed events
        public void sendAllowed(ConnectionEvent event) {
    * do nothing for accept events
        public void accept(ConnectionEvent event) {
    * called once per second by the server main thread.
        public void oneSec() {
            if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
                close(true);
    * send a message
        private void send(String msg) {
            conn.send(msg);
            remainingTime.set(idleTime);
    * forward data messages to other users
    * @param txt the message to send
        private void forward(String txt) {
            txt = name+": "+txt + "\n";
            if(0 < targets.length) {
                for(String target :targets) {
                    User user = perUser.get(target);
                    if(user != null) {
                        user.send(txt);
            } else {
                for (User user : perUser.values()) {
                    if (user != this) {
                        user.send(txt);
    * execute command messages, commands start with a $
    * and contain arguments delimited by white space.
    * @param command the command string
        private void doCommand(String command) {
            boolean good = false;
            command = command.substring(1).trim();
            if(command.length() > 0) {
                String [] args = command.split("\\s+");
                if(args[0].equals("on")) {
                    good = signOn(args);
                } else if(args[0].equals("off")) {
                    good = signOff(args);
                } else if(args[0].equals("list")) {
                    good = listUsers(args);
                } else if(args[0].equals("to")) {
                    good = setTargets(args,1);
                } else if(args[0].equals("idle")) {
                    good = setIdle(args);
                if(!good) {
                    send("invalid command=" + command + "\n");
    * sign on command
        private boolean signOn(String [] args) {
            boolean good = false;
            if(args.length >1) {
                String nm = args[1];
                logger.info("signing on as: " + nm);
                if(rename(nm)) {
                    conn.setName(name);
                    send("Signed on as " + name + "\n");
                    signedOn = true;
                    good = true;
                    setTargets(args,2);
                } else {
                    send("name="+nm+" already signed on\n");
            return good;
    * set forwarding targets
        private boolean setTargets(String [] args, int start) {
            if(start < args.length) {
                targets = new String[args.length-start];
                System.arraycopy(args, start, targets, 0, targets.length);
            String str = "to=";
            for(String target : targets) {
                str += (target + " ");
            send(str+"\n");
            return true;
    * set idle timeout
        private boolean setIdle(String[] args) {
            try {
                idleTime = new Integer(args[1]).intValue();
                remainingTime.set(idleTime);
                send("idle time set to "+idleTime+"\r\n");
                return true;
            } catch(NumberFormatException exc) {
                return false;
    * sign off
        private boolean signOff(String [] args) {
            close(true);
            return true;
    * list connected users
        private boolean listUsers(String [] args) {
            TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
            HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
            LinkedList<String> users;
            String response = "On,Target,Nickname\n";
            if(args.length < 2) {
                users = new LinkedList<String>(allUsers);
            } else {
                users = new LinkedList<String>();
                for (int i = 1; i < args.length; i++) {
                    users.add(args);
    for(String username : users) {
    if(username.equals(name)) {
    response += "*,";
    } else {
    response += (allUsers.contains(username) ? "y," : "n,");
    response += (t.contains(username) ? "y," : "n,");
    response += (username + "\n");
    send(response);
    return true;
    * rename this user, first we attempt to add the new name then we remove
    * the old one. Both names will be registered for a short while.
    * @param newname the new name for this user
    * @return true if the rename was successful
    private boolean rename(String newname) {
    boolean b = false;
    logger.info("rename name="+name+" newname="+newname);
    if (name != null && name.equals(newname)) {
    b = true;
    } else if (null == perUser.putIfAbsent(newname, this)) {
    if (name != null) {
    perUser.remove(name);
    name = newname;
    b = true;
    return b;
    * delete from perUser and close our connection
    private void close(boolean disconnect) {
    logger.info("closing user "+name);
    perUser.remove(name);
    if (disconnect) {
    conn.disconnect();
    //====================== Connection.java ===============================//
    package pkwnet.msgswitch;
    import java.util.HashSet;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public abstract class Connection {
    public enum State {CLOSED, OPENING, OPENED, CLOSING}
    private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
    private State state = State.CLOSED;
    private String host = "127.0.0.1";
    private int port = 6060;
    private String name = "unconnected";
    public Connection() {
    public abstract void listen(int port);
    public abstract void connect(String address);
    public abstract void disconnect();
    public abstract void send(String message);
    public void addConnectionListener(ConnectionListener listener) {
    listeners.add(listener);
    public void removeConnectionListener(ConnectionListener listener) {
    listeners.remove(listener);
    protected void fireDataAvailable(String data) {
    for (ConnectionListener listener : listeners) {
    listener.dataAvailable(new ConnectionEvent(this, state, data));
    private void fireStateChanged() {
    for (ConnectionListener listener : listeners) {
    listener.stateChanged(new ConnectionEvent(this, state));
    protected void fireSendAllowed() {
    for (ConnectionListener listener : listeners) {
    listener.sendAllowed(new ConnectionEvent(this, state));
    protected void fireAccept(Connection conn) {
    for (ConnectionListener listener : listeners) {
    listener.accept(new ConnectionEvent(this, conn));
    protected void setState(State state) {
    if (this.state != state) {
    this.state = state;
    fireStateChanged();
    public State getState() {
    return state;
    protected void setAddress(String address) {
              int n = address.indexOf(':');
              String pt = null;
    setName(address);
    if(n == 0) {
                   host = "127.0.0.1";
                   pt = address.substring(1);
              else if(n < 0) {
                   host = address;
                   port = 5050;
              } else {
    host = address.substring(0,n);
                   pt = address.substring(n+1);
    if (pt != null) {
    try {
    port = Integer.parseInt(pt);
    } catch (NumberFormatException e) {
    port = -1;
    public String getName() {
    return name;
    public void setName(String value) {
    name = value;
    public String getAddress() {
    return host + ":" + port;
    public String getHost() {
    return host;
    public void setPort(int value) {
    port = value;
    public int getPort() {
    return port;
    //=================== ConnectionEvent.java ================================//
    package pkwnet.msgswitch;
    public class ConnectionEvent extends java.util.EventObject {
    private final String data;
    private final Connection.State state;
    private final Connection conn;
    public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
    super(source);
    this.state = state;
    this.data = data;
    this.conn = conn;
    public ConnectionEvent(Object source, Connection.State state, String data) {
    this(source, state, data, null);
    public ConnectionEvent(Object source, Connection.State state) {
    this(source, state, null, null);
    public ConnectionEvent(Object source, Connection conn) {
    this(source, conn.getState(), null, conn);
    public Connection.State getState() {
    return state;
    public String getData() {
    return data;
    public Connection getConnection() {
    return conn;
    //============================ ConnectionListener.java ===================//
    package pkwnet.msgswitch;
    public interface ConnectionListener extends java.util.EventListener {
    public void stateChanged(ConnectionEvent event);
    public void dataAvailable(ConnectionEvent event);
    public void sendAllowed(ConnectionEvent event);
    public void accept(ConnectionEvent event);
    //============================ StreamConnection.java ===================//
    package pkwnet.msgswitch;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * provides stream socket i/o of character strings
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class StreamConnection extends Connection {
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread = null;
    private Thread sendThread = null;
    protected LinkedBlockingQueue<String> sendQ;
    Logger logger;
    public StreamConnection() {
    super();
    logger = Logger.getLogger("msgswitch.stream");
    sendQ = new LinkedBlockingQueue<String>();
    * open a socket and start i/o threads
    public void connect(String ipAddress) {
    setAddress(ipAddress);
    try {
    sock = new Socket(getHost(), getPort());
    connect(sock);
    } catch (IOException e) {
    logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
    private void connect(Socket sock) {
    this.sock = sock;
    String ipAddress = getAddress();
    try {
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv." + getName());
    sendThread = new Thread(new Runnable() {
    public void run() {
    doSend();
    },"Send."+getName());
    sendThread.start();
    recvThread.start();
    setState(State.OPENED);
    } catch(IOException e) {
    logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
    public void listen(int port) {       
    StreamConnection sconn;
    setPort(port);
    try {
    ServerSocket ss = new ServerSocket(port);
    while(true) {
    Socket us = ss.accept();
    sconn = new StreamConnection();
    String ipAddress = us.getInetAddress() + ":" + us.getPort();
    sconn.setAddress(ipAddress);
    sconn.connect(us);
    fireAccept(sconn);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "listen failed", e);
    * close the socket connection
    public void disconnect() {
    logger.fine("disconnect sock=" + sock + " state="+ getState());
    if(getState() == State.OPENED) {
    setState(State.CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    logger.log(Level.SEVERE, "showdown failed", ie);
    } else if(getState() != State.CLOSED) {
    try {
    sock.close();
    } catch(Exception e) {
    logger.log(Level.SEVERE, "close failed", e);
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    sendQ.clear();
    setState(State.CLOSED);
    public void send(String message) {
    if (getState() == State.OPENED) {
    try {
    sendQ.put(message);
    } catch(InterruptedException e) {
    logger.log(Level.SEVERE, "sendQ put interrupted", e);
    setState(State.CLOSING);
    disconnect();
    * sets the public name of this connection
    public void setName(String name) {
    super.setName(name);
    if (sendThread != null) {
    try {
    recvThread.setName("recv." + name);
    sendThread.setName("send." + name);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "nameing threads failed", e);
    * the main loop for the send thread
    private void doSend() {
    String msg;
    boolean running = true;
    while (running) {
    if (sendQ.size() == 0) {
    fireSendAllowed();
    try {
    msg = sendQ.take();
    out.write(msg);
    out.flush();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "write failed", e);
    setState(State.CLOSING);
    disconnect();
    running = false;
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (getState() == State.OPENED) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "readline failed", e);
    inbuf = null;
    if(inbuf == null) {
    logger.fine("null received on: " + getAdd

    Here are three of them:
    NIO server
    NIO client
    Multithreaded server
    The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it.

Maybe you are looking for

  • How to remove spaces in the output of an PL/SQL report

    Hi, The requirement is to develop a SQL report. The sample code is like this Select 'Order Number Header Id' from dual; ( This is the heading in the output of the report.) Select order_number , header_id from oe_order_headers_all; The output is displ

  • How can I save preview files to other than C: drive?

    My development machine has multiple drives and network drives. The C:/ drive is the oldest, slowest and fullest. I am using Elements, but have used Premiere over the years. Back then, we could make the program work better by off-loading files from C:

  • Keyboard shipped with Pavilion non-standard number keypad

    Hello, I advised a friend to buy an HP Pavilion 550 desktop for use at her office. She is a bookkeeper and relies heavily on the number pad on the right side of the keyboard. The keyboard that shipped has a non-standard numeric keypad where the "0" k

  • Airport Express WiFi network MAC address filtering not working

    I have an Airport Express WiFi network which I bought and installed new in 2011. Initially I enabled MAC address access control and populated a list. It was working perfectly, I know, because a niece visiting tried to connect her iPhone and could not

  • Time access control does not work

    I set up the time access control for my kids devices, but they can still access the internet.