HTTP Web Proxy using Non Blocking IO

Resolved Thanks................

client.register(selector, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);OP_READ only at this stage. OP_WRITE is always 'ready' unless the socket send buffer is full, so your selector will just spin. Don't register OP_WRITE until you have something to write.
ByteBuffer bferClient = ByteBuffer.allocate(4096);You're doing this every time around the loop, and you don't even know whether the key is readable yet. Do it when you accept a connection, and save it as the key attachment for that channel.
client.configureBlocking(false);It's already in non-blocking mode. Why are you doing this again?
try {
if ((bytesRead = client.read(bferClient)) != -1) {
bferClient.flip();
String msgFromClient = new String(bferClient.array());new String(bferClient.array(), 0, bferClient.limit()-1), but you're assuming you got a complete command here. You may not have. That's another reason why you need a ByteBuffer per channel.
channel.connect(socketAddress);You should do that in non-blocking mode, register the channel for OP_CONNECT, and let the select loop take care of finishing the connection.
channel.write(bferClient);The incoming command was CONNECT. You don't write that upstream.
if (!"".equals(msgFromClient.trim())) {
int bytesReadServer;
byte[] reply = new byte[4096];
try {
ByteBuffer bufferNIO = ByteBuffer.allocateDirect(1024);
while ((channel.read(bufferNIO)) != -1) {
bufferNIO.flip();
client.write(bufferNIO);
bufferNIO.clear();
}And you don't do any of this here. You register the new channel for OP_CONNECT, then when you get that do finishConnect() and then register it for OP_READ, and proceed around your select loop. You also need to associate this channel with the channel you read the CONNECT from. So you really need a key attachment object for the original channel that contains its byte buffer and the upstream channel; similarly the upstream channel needs a key attachment that contains its buffer and its downstream channel. The effect of doing all this stuff here instead of around the select loop is that you are never getting back to the select loop: you are handling this one client here, in blocking mode, until the connection is dropped. Completely wrong.
} catch (IOException e) {Hang on. If bytesRead was -1 you must close the channel.
e.printStackTrace();And if you get any IOException here you must also close the channel.
if (channel != null) {
try {
channel.close();This is a really strange place to close this channel.
When you get all that fixed up, post your code and I'll tell you how to handle OP_WRITE.

Similar Messages

  • Java.io.IOException: Connection timed out while using non-blocking NIO

    Hi,
    I am using non-blocking NIO on jdk 1.6 to transfer files between two processes. The problem is that the sender thread times out on the write call even though it's in non-blocking mode. It doesn't make sense. The receiver on the other end is running fine, and even tries to read from the socket after the sender drops the connection, and throws a Connection reset by peer exception. I should mention that the receiver is sometimes busy doing other stuff, and may be a second or two late in issuing the read call. But if I understand correctly, default TCP timeout is about 2 minutes, so there's no reason why it should timeout in a second or two. I'd appreciate it if anyone has any insight.
    Thanks!

    No I have definitely completed the connection since I it happens a while after the transfer has actually started and part of the file has already been transferred. Oh btw, I should mention that it doesn't always happen. It's intermittent. And it's not a network issue since iperf tests between the two nodes show nothing unusual.

  • Http web proxy doesn't work after iOS 8.0 upgrade

    Hi ,
    I upgraded my ipad air to ios 8. But after this change I am not able to connect to any web site through http web proxy. I think this has to be related io8 specifaciton.
    Please let me know any solution for this.
    Regards ,
    Gokhan

    Ever since the iOS 8.0.2 update my iphone 4 will not update any of my apps. I have 12 apps stuck on updates. Is anyone listening at Apple?

  • 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.

  • Jax-ws 2.2.8 and ws-addressing: Client throwing java.lang.NullPointerException on receipt of HTTP 202 when using non-anonymous ReplyTo address

    Server: JBoss EAP 6.2.0
    Client: JDK 1.7.0_51 x64
    JAX-WS: RI 2.2.8 ( via -Djava.endorsed.dirs )
    I am getting a java.lang.NullPointerException when calling the operation on the WS endpoint from the client when using non-anonymous replyTo address.
    I have simplified the scenario into a small test case that hopefully others can replicate. Since the exception is happening on the client instead of the server, I would think that the container used is irrelevant, but I have specified it nonetheless.
    1) WebService:
    package test.webservice;
    import java.util.Random;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    import javax.xml.ws.soap.Addressing;
    @WebService(targetNamespace="http://services.nowhere.org/")
    @Addressing(required=true)
    @SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
    public class RandomTest {
        @WebMethod
        public long nextRandom(@WebParam boolean forceException) throws Exception {
            if( forceException ) {
                throw new Exception("Some exception");
            Random rand = new Random();
            return rand.nextLong();
    2) Generated WSDL by JBossEAP 6.2.2:
    <?xml version='1.0' encoding='UTF-8'?><wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:tns="http://webservice.test/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="RandomTestService" targetNamespace="http://webservice.test/">
      <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://webservice.test/" elementFormDefault="unqualified" targetNamespace="http://webservice.test/" version="1.0">
      <xs:element name="nextRandom" type="tns:nextRandom"/>
      <xs:element name="nextRandomResponse" type="tns:nextRandomResponse"/>
      <xs:complexType name="nextRandom">
        <xs:sequence/>
      </xs:complexType>
      <xs:complexType name="nextRandomResponse">
        <xs:sequence>
          <xs:element name="return" type="xs:long"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
      </wsdl:types>
      <wsdl:message name="nextRandom">
        <wsdl:part element="tns:nextRandom" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:message name="nextRandomResponse">
        <wsdl:part element="tns:nextRandomResponse" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:portType name="RandomTest">
        <wsdl:operation name="nextRandom">
          <wsdl:input message="tns:nextRandom" name="nextRandom" wsam:Action="http://webservice.test/RandomTest/nextRandomRequest" wsaw:Action="http://webservice.test/RandomTest/nextRandomRequest">
        </wsdl:input>
          <wsdl:output message="tns:nextRandomResponse" name="nextRandomResponse" wsam:Action="http://webservice.test/RandomTest/nextRandomResponse" wsaw:Action="http://webservice.test/RandomTest/nextRandomResponse">
        </wsdl:output>
        </wsdl:operation>
      </wsdl:portType>
      <wsdl:binding name="RandomTestServiceSoapBinding" type="tns:RandomTest">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsaw:UsingAddressing wsdl:required="true"/>
        <wsp:PolicyReference URI="#RandomTestServiceSoapBinding_WSAM_Addressing_Policy"/>
        <wsdl:operation name="nextRandom">
          <soap:operation soapAction="" style="document"/>
          <wsdl:input name="nextRandom">
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output name="nextRandomResponse">
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="RandomTestService">
        <wsdl:port binding="tns:RandomTestServiceSoapBinding" name="RandomTestPort">
          <soap:address location="http://localhost:8080/servertest/RandomTest"/>
        </wsdl:port>
      </wsdl:service>
        <wsp:Policy xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="RandomTestServiceSoapBinding_WSAM_Addressing_Policy"><wsam:Addressing><wsp:Policy/></wsam:Addressing></wsp:Policy>
    </wsdl:definitions>
    3) ant build.xml to generate the client code from WSDL
    <?xml version="1.0" encoding="UTF-8"?>
    <project default="build" basedir="..">
        <property name="jaxws.classpath" location="C://jaxws-2.2.8/jaxws-ri/lib/*.jar"/>
        <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
               <classpath path="${jaxws.classpath}"/>
        </taskdef>
        <target name="build" >
            <!-- For these to work, the JAR files in tools/jaxws-ri must be included in Ant's classpath -->
            <wsimport wsdl="http://localhost:8080/servertest/RandomTest?wsdl"
                   verbose="true"
                   sourcedestdir="src"
                   destdir="bin"
                   keep="true">
                   <xjcarg value="-enableIntrospection"/>
            </wsimport>
        </target>
    </project>
    4) Client code
    4a) ClientTest.java - Actual client run from client
    package test.wsclient;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.ws.BindingProvider;
    import javax.xml.ws.Endpoint;
    import javax.xml.ws.handler.Handler;
    import javax.xml.ws.soap.AddressingFeature;
    import org.nowhere.services.RandomTest;
    import org.nowhere.services.RandomTestService;
    public class ClientTest {
        public static void main(String args[]) throws Exception {
            ClientTest app = new ClientTest();
            app.testAddressing();
        public void testAddressing() throws Exception {
            String REPLY_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallback";
            String FAULT_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallbackFault";
            RandomTestService service = new RandomTestService();
            RandomTest port = service.getRandomTestPort(new AddressingFeature());
            BindingProvider provider = (BindingProvider) port;
            // pass the replyTo address to the handler
            provider.getRequestContext().put("ReplyTo", REPLY_TO_ADDRESS);
            provider.getRequestContext().put("FaultTo", FAULT_TO_ADDRESS);
            // Register handlers to set the ReplyTo and FaultTo on the SOAP request sent to the WS endpoint
            List<Handler> handlerChain = new ArrayList<Handler>();
            handlerChain.add(new ClientHandler());
            provider.getBinding().setHandlerChain(handlerChain);
            // Start endpoint to receive callbacks from WS
            Endpoint endpoint = Endpoint.publish(REPLY_TO_ADDRESS, new CallbackSEI());
            try {
                port.nextRandom(false);
            } catch( Exception ex ) {
                ex.printStackTrace();
            } finally {
                Thread.sleep(10000);
            endpoint.stop();
            System.exit(0);
    4b) ClientHandler.java - Used to set the wsa ReplyTo address and FaultTo address when sending SOAP request from client to server
    package test.wsclient;
    import java.util.Set;
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.MessageContext.Scope;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class ClientHandler implements SOAPHandler<SOAPMessageContext> {
        public ClientHandler() {};
        @Override
        public Set<QName> getHeaders() {
            return null;
        @Override
        public void close(MessageContext arg0) {
        @Override
        public boolean handleFault(SOAPMessageContext context) {
            return true;
        protected void setAnAddress(SOAPHeader header, String tagName, String address) {
            NodeList nodeListReplyTo = header.getElementsByTagName(tagName);
            NodeList nodeListAddress = nodeListReplyTo.item(0).getChildNodes();
            for (int i = 0; i < nodeListAddress.getLength(); i++) {
                Node node = nodeListAddress.item(i);
                if ("Address".equals(node.getLocalName())) {
                    node.setTextContent(address);
                    break;
        protected String getMessageID(SOAPHeader header) {
            NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
            return nodeListMessageId.item(0).getTextContent();
        @Override
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean isOutbound = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (isOutbound) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPHeader header = envelope.getHeader();
                    /* extract the generated MessageID */
                    String messageID = getMessageID(header);
                    context.put("MessageID", messageID);
                    context.setScope("MessageID", Scope.APPLICATION);
                    /* change ReplyTo address */
                    setAnAddress(header, "ReplyTo", (String) context.get("ReplyTo"));
                    setAnAddress(header, "FaultTo", (String) context.get("FaultTo"));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
            return true;
    4c) CallbackSEI.java - endpoint on the client for server to send the SOAP response back to the client
    package test.wsclient;
    import javax.annotation.Resource;
    import javax.jws.Oneway;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.ws.Action;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.WebServiceContext;
    import javax.xml.ws.soap.Addressing;
    @WebService
    @Addressing
    //@HandlerChain(file = "/handler-chain.xml")
    public class CallbackSEI {
        @Resource
        private WebServiceContext context;
         * If there is no namespace specified in the method below, then the CallbackSEI needs to be in the same package as the
         * WS endpoint.
        @Oneway
        @Action(input="http://services.nowhere.org/RandomTest/nextRandomResponse")
        @RequestWrapper(localName="nextRandomResponse", targetNamespace="http://services.nowhere.org/")
        public void handleNotification(@WebParam(name="return")long random) {
            System.out.println("Asynch response received");
            System.out.println( random );
            //System.out.println("This response relates to the message ID: "+ getMessageID());
    In summary:
    Server is listening on port 8080
    Client will listen in port 8082 for the callback from the server for the SOAP response
    Now when I run the client, I see that the proper behaviour as far as ws-addressing is concerned. That is:
    client  -- SOAP request ( on port 8080 ) --> server
    client <-- HTTP 202 ( empty HTTP body )  --- server
    client <-- SOAP response ( on port 8082 )  --- server
    All well and good, except that I am getting a NullPointerException on the client side when I call the operation.
    With debugging of the SOAP request and responses, I get the following output:
    ---[HTTP request - http://localhost:8080/servertest/RandomTest]---
    Accept: text/xml, multipart/related
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://services.nowhere.org/RandomTest/nextRandomRequest"
    User-Agent: JAX-WS RI 2.2.8 svn-revision#13980
    <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><S:Header><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8080/servertest/RandomTest</To><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomRequest</Action><ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallback</Address>
    </ReplyTo><FaultTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallbackFault</Address>
    </FaultTo><MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</MessageID></S:Header><S:Body><ns2:nextRandom xmlns:ns2="http://services.nowhere.org/"><arg0>false</arg0></ns2:nextRandom></S:Body></S:Envelope>--------------------
    ---[HTTP response - http://localhost:8080/servertest/RandomTest - 202]---
    null: HTTP/1.1 202 Accepted
    Content-Length: 0
    Content-Type: text/xml;charset=UTF-8
    Date: Fri, 18 Jul 2014 08:34:36 GMT
    Server: Apache-Coyote/1.1
    java.lang.NullPointerException
        at com.sun.proxy.$Proxy38.nextRandom(Unknown Source)
        at test.wsclient.ClientTest.testAddressing(ClientTest.java:43)
        at test.wsclient.ClientTest.main(ClientTest.java:18)
    ---[HTTP request]---
    Cache-control: no-cache
    Host: localhost:8082
    Content-type: text/xml; charset=UTF-8
    Content-length: 704
    Connection: keep-alive
    Pragma: no-cache
    User-agent: Apache CXF 2.7.7.redhat-1
    Accept: */*
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomResponse</Action><MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:65d8d7fc-09e4-494a-a9c5-0a01faf4d7e6</MessageID><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8082/servertest/RandomCallback</To><RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</RelatesTo></soap:Header><soap:Body><ns2:nextRandomResponse xmlns:ns2="http://services.nowhere.org/"><return>2870062781194370669</return></ns2:nextRandomResponse></soap:Body></soap:Envelope>--------------------
    Asynch response received
    2870062781194370669
    As you can see from the output above, the proxy is throwing an Exception when it receives the HTTP 202 response.
    Any ideas ?

    I think I have found when I get this error and probably I have found a bug. I will appreciate if someone can confirm this.
    In my BPEL project setup, my BPEL process's wsdl file imports another wsdl from different namespace. Here is sample snippet -
    <wsdl:definitions targetNamespace="http://namespace/1">
    <wsdl:import namespace="http://namespace/2" location="resources/another.wsdl"/>
    <plnk:partnerLinkType....../>
    </wsdl:definitions>
    Please let me know. I checked the bundled samples with Oracle BPEL PM and did not find any similar case where process wsdl imports another wsdl.
    Thank you.
    Meghana

  • Using non blocking connect() call for SCTP sockets in Solaris10

    Hi,
    I have a problem with non blocking connect call on SCTP socket.
    I am using the sctp stack support in Solaris10.
    When the connect is successful, I can get the pollout event on the socket.
    But there is no event observed when the peer does not exist. In other words, I could not get the pollout event on connection failure. This logic works fine with TCP sockets on both Solaris and Suse10.
    I am working with SCTP one-to-one style sockets.
    Is there any way to handle this issue?
    Do I need to load any patch to resolve this issue?
    It will be great if I get a solution in this regard.
    Thanks in advance.
    Best Regards,
    Bipin.

    There are at least two problems here.
    A. In the receiver you should test for -1 from the read() immediately, rather than continue with the loop and try to write -1 bytes to the file.
    B. In the sender you are ignoring the return value of client.write(), which can be anything from 0 to the buffer length. If you get 0 you should wait for another OP_WRITE to trigger; if you get a 'short write' you need to retry it until you've got nothing left to write from the current buffer, before you read any more data. This is where the data is vanishing.

  • FileChannel.transferTo() using non-blocking SocketChannel

    I'm looking to use FileChannel.transfer(From/To) for performing file transfers over a network. On the uploading side I find that even though I set the SocketChannel to non-blocking mode, the loop manages to send files as large as 30MB in only a single transferTo() invocation. What I'm hoping for is to have a series of partial writes so that I might generate progress notifications, which does occur on the downloading side with transferFrom(). I don't think a file that large should be transferred in one pass so I'm thinking that this is caused by either some internal buffer allocation issue or a goof-up on my part.
    Thanks in advance for any input and here's the uploading code:
    public void upload( String fileName ) {
    FileInputStream fileStrm = null;
    FileChannel fileChan = null;
    FileLock fileLock = null;
    SocketChannel sockChan = null;
    Selector selector = null;
    try {
    // Lock the source file.
    file = new File( fileName );
    fileStrm = new FileInputStream( file );
    fileChan = fileStrm.getChannel();
    fileLock = fileChan.lock( 0L, Long.MAX_VALUE, true );
    // Open a server socket bound to an arbitrary port.
    servChan = ServerSocketChannel.open();
    servChan.socket().bind( new InetSocketAddress( 0 ) );
    // Wait for a single connection and close the server socket.
    sockChan = servChan.accept();
    servChan.close();
    sockChan.configureBlocking( false );
    selector = Selector.open();
    SelectionKey selectorKey = sockChan.register( selector, SelectionKey.OP_WRITE );
    // Loop until transfer has completed.
    int fileSize = ( int ) file.length();
    int sizeLeft = fileSize;
    while ( sizeLeft > 0 ) {
    // Wait for data to read, then transfer it.
    if ( selector.select() == 1 && selectorKey.isWritable() ) {
    sizeLeft -= ( int ) fileChan.transferTo( fileSize - sizeLeft, sizeLeft, sockChan );
    // Generate a progress notification here such as:
    // monitor.bytesTransferred( fileSize - sizeLeft );
    catch ( IOException ex ) {
    ex.printStackTrace();
    finally {
    try {
    // Cleanup.
    if ( selector != null )
    selector.close();
    if ( sockChan != null )
    sockChan.close();
    if ( fileLock != null )
    fileLock.release();
    if ( fileChan != null )
    fileChan.close();
    if ( fileStrm != null )
    fileStrm.close();
    catch ( IOException ex ) {
    ex.printStackTrace();
    -Edwin

    Actually, the sending process appears way ahead of the receiving one, where the send seems to finish in a blink while the receive takes several seconds to complete. In other words, the transferTo() completes in one loop, while the transferFrom() performs many with delays in between. I'd guess all that data is sitting in some large outbound buffer at the sender, which would explain why it seems to finish too quickly. If I split the send into smaller chunks, the two sides run quite nearly at the same pace as expected.
    The receiver already sleeps by way of a select() against a non-blocking SocketChannel, so I'll try reducing the buffer sizes as you suggest.

  • Using non-blocking NIO, need Main Thread wait?

    I'm trying to utilize the New IO libraries to create a simple url check application. The application just tests return codes to make sure the list of urls I have are still valid.
    I'm using the NIO libraries because I had problems with the URLConnection object hanging when I ran into a url where the server never replied. It just sat there waiting for a reply.
    Now I have a new problem, the connection to the web server is now in a new thread and I need to wait for the connection to finish before using it. I can't figure out how to make the main app wait for the connection. All of the documentation I find for the Wait() method refers to threads and I can't find how to refer to the main application thread.
    Any suggestions?
    Josh

    Ok, this is were I have some gaps in my Java knowledge. How do I wait for OP_CONNECT to fire. Is it like setting up a ActionListener but for a non-visual object?
    Also what do you mean when you refer to deregistering it?
    You don't need to explain everything. I would be happy if I was just pointed at the appropriate pages and I'll do the leg work.
    Josh
    If you're using NIO the connection can be handled in
    the same thread as the I/O. Just wait for OP_CONNECT
    to fire, deregister it, and away you go.

  • Web Proxy using Flex 2?

    Hey everyone,
    I'm trying to create a proxy service similar to sites like
    proxy7.com in Flex, but I'm having extreme difficulties. Right now
    I just want to get the basics, so I'm trying to load basic sites
    like google.com. Here is the script I have so far:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" width="50%" height="50%">
    <mx:HTTPService id="loadSite" method="get" />
    <mx:states>
    <mx:State name="sent" >
    <mx:SetProperty target="{panel1}" name="height"
    value="95%"/>
    <mx:SetStyle target="{panel1}" name="borderColor"/>
    <mx:AddChild relativeTo="{panel1}"
    position="lastChild">
    <mx:TextArea creationComplete="getPage.send()"
    id="siteDisp" top="43" right="10" bottom="10" left="10"
    htmlText="{getPage.lastResult.toString()}" />
    </mx:AddChild>
    </mx:State>
    </mx:states>
    <mx:Panel width="95%" height="85" layout="absolute"
    verticalCenter="0" horizontalCenter="0" title="Josh's Proxy"
    id="panel1" resizeEffect="Resize" >
    <mx:TextInput id="urlin" top="10" left="10" right="70"
    editable="true" text="Enter URL here..." focusIn="if(urlin.text ==
    'Enter URL here...'){ urlin.text = '
    http://' }" height="25"/>
    <mx:Button label="Go" width="50" right="10" top="10"
    height="25" click="getPage.send()" id="button1" />
    </mx:Panel>
    <mx:HTTPService id="getPage" url="{urlin.text}"
    resultFormat="text" showBusyCursor="true"
    result="currentState='sent'" />
    </mx:Application>
    It starts to work a little bit, but all it returns is
    "Google". Any suggestions?

    Are you using Flex Builder 3? Flex 3.0 beta Data
    visualization components are available as part of FB 3 only. You
    can select either 2.0.1 hotfix 3 charts (consists of only
    charts.swc) or 3.0.0 data visualization (consists of
    datavisualization.swc). through multiple sdks feature of FB3. For
    flex 3 beta, flex 2 charting key will work. so if you want to try
    out new features in charts and new components like Advanced data
    grid you can switch to 3.0.0 sdk and use same flex 2 charting key
    to remove watermark from charts.

  • Connecting to http web site using java socket

    Hi,
    Sockets in Java I believe are reusable. Once created, it can be used to send a request using its input stream and get back a response using the output stream. My problem is I am trying to connect to a website using java socket but I am unable to get a response (though the same works fine I use URL and URLConnection). Can anyone tell me whats wrong? Below is the client program:
    public class HttpAdapterTest {
         public static void main(String[] args) {
              try {
                   Socket socket = new Socket("www.google.com", 80);
                   BufferedWriter out = new BufferedWriter(
                                  new OutputStreamWriter(socket.getOutputStream()));
                   out.write("GET /help/basics.html HTTP/1.1");
                   out.flush();
                   BufferedReader in = new BufferedReader(
                                            new InputStreamReader(ucon.getInputStream()));
                   String line = null;
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                   in.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Look at the JSSE examples. You need to setup a key store, add the jsse jars to your classpath, yadda, yadda, yadda....

  • File transfer using non-blocking sockets - data mysteriously  vanish

    Hello,
    I need to pass some big amount of data using sockets. I my appliaction I have noticed that sometimes I didn't get all bytes. To check it out I wrote simple client + server to figure out what is happening. So:
    - I have a sender and receiver application
    - I'm trying to transfer 5MB text file.
    - On receiver side, output file is never larget than 3MB
    - If I put some timeout on sender side (1ms timeout between write operations) everything works fine.
    Could someone tell me what I do wrong? Why data disappears and when? The same file transfered using old sockets goes always fine...
    Thanks in advance!
    Here is complete source for receiver and sender:
    RECEIVER:
    import java.io.FileOutputStream;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    public class ReceiverA {
          * @param args
         public static void main(String[] args) {
              String outputFile = "c:\\outputA.txt", host = "127.0.0.1";          
              int port = 8001, bufferSize = 10240;
              try {
                   ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
                   Selector selector = Selector.open();
                   ServerSocketChannel server = ServerSocketChannel.open();
                   server.configureBlocking(false);
                   server.socket().bind(new InetSocketAddress(host, port));
                   server.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Server started");
                   while(true)
                        selector.select();
                        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                        while (iterator.hasNext()) {
                             SelectionKey key = (SelectionKey) iterator.next();
                             iterator.remove();
                             if (key.isAcceptable()) {                              
                                  SocketChannel client = server.accept();
                                  client.configureBlocking(false);
                                  client.register(selector, SelectionKey.OP_READ);                              
                                  continue;
                             SocketChannel channel = (SocketChannel) key.channel();
                             int counter = 1;
                             if ( key.isReadable() ) {
                                  FileOutputStream os = new FileOutputStream(outputFile);
                                  int res;
                                  do
                                       buffer.clear();
                                       res = channel.read(buffer);
                                       counter += res;
                                       System.out.println(res);
                                       buffer.flip();
                                       os.write(buffer.array(), 0, buffer.limit());
                                  while( res >= 0 );          
                                  channel.close();
                                  os.close();          
                                  System.out.println("Receiver: " + counter);
                                  return;
              } catch (Exception e) {
                   e.printStackTrace();
    }SENDER:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    public class SenderA {
         public static void main(String[] args) {
              String inputFile = "c:\\inputA.txt" , host = "127.0.0.1";          
              int port = 8001, bufferSize = 10240;
              try {
                   ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
                   byte[] byteArr = new byte[buffer.capacity()];
                   Selector selector = Selector.open();
                   SocketChannel connectionClient = SocketChannel.open();     
                   connectionClient.configureBlocking(false);
                   connectionClient.connect(new InetSocketAddress(host, port));
                   connectionClient.register(selector, SelectionKey.OP_CONNECT);
                   while(true) {
                        selector.select();
                        Iterator<SelectionKey> iterator = selector.selectedKeys()
                                  .iterator();
                        while (iterator.hasNext()) {
                             SelectionKey key = (SelectionKey) iterator.next();
                             iterator.remove();
                             SocketChannel client = (SocketChannel) key.channel();
                             if (key.isConnectable()) {
                                  if (client.isConnectionPending()) {
                                       System.out.println("Trying to finish connection");
                                       try {
                                            client.finishConnect();
                                       } catch (IOException e) {
                                            e.printStackTrace();
                                  client.register(selector, SelectionKey.OP_WRITE);
                                  continue;
                             if(key.isWritable()) {
                                  FileInputStream is = new FileInputStream(inputFile);
                                  int res;
                                  int counter = 0;
                                  do
                                       buffer.clear();
                                       res = is.read(byteArr, 0, byteArr.length);                                   
                                       System.out.println(res);
                                       if ( res == -1 ) break;
                                       counter += res;
                                       buffer.put(byteArr, 0, Math.min(res, buffer.limit()));
                                       buffer.flip();
                                       client.write(buffer);
                                        * When I remove comment file transfer goes OK!
                                       //Thread.sleep(1);
                                  while( res != -1 );          
                                  client.close();
                                  is.close();          
                                  System.out.println("Receiver: " + counter);
                                  return;
              catch(Exception e) {
                   e.printStackTrace();
    }

    There are at least two problems here.
    A. In the receiver you should test for -1 from the read() immediately, rather than continue with the loop and try to write -1 bytes to the file.
    B. In the sender you are ignoring the return value of client.write(), which can be anything from 0 to the buffer length. If you get 0 you should wait for another OP_WRITE to trigger; if you get a 'short write' you need to retry it until you've got nothing left to write from the current buffer, before you read any more data. This is where the data is vanishing.

  • New to Web Services - need to call a HTTPS web service from PL/SQL

    I am new to Web Services and need to call HTTPS web service from PL/SQL program. I am using 10g Database.
    I have been reading there are 2 options -
    1. UTL_HTTP - with this package its possible to call HTTPS web services
    2. UTL_DBWS
    Questions -
    1. Is it possible to call a HTTPS web service using UTL_DBWS ? I have not been able to find any information on it.
    2. Can someone point me to UTL_HTTP and UTL_DBWS examples calling a HTTPS web service ?
    3. The HTTPS web service that I need to call needs username/password to connect - how will I incorporate this in the pl/sql code ?
    Appreciate the help.
    Cheers,
    newWebServicesUser

    Hi,
    1. UTL_DBWS not work for https from what I understand
    2. Here is a sample example:
    [http://www.oracle-base.com/articles/9i/ConsumingWebServices9i.php#]
    Be careful, you must change http/1.0 IN 1.1 inside package SOAP_API.
    Here is an example for a prime number where the SOAP message is already construct:
    CREATE OR REPLACE procedure test_ws_2
    IS
    http_req utl_http.req;
    http_resp utl_http.resp;
    request_env varchar2(32767);
    response_env varchar2(32767);
    begin
    -- Set proxy details if no direct net connection.
    UTL_HTTP.set_proxy('http://<USER>:<PASS>@10.0.2.21:8070', NULL);
    UTL_HTTP.set_persistent_conn_support(TRUE);
    request_env:='<?xml version="1.0" encoding="utf-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">'||
    '<SOAP-ENV:Body><GetPrimeNumbers xmlns="http://microsoft.com/webservices/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'||
    '<max xsi:type="xsd:int">10</max>'||
    '</GetPrimeNumbers></SOAP-ENV:Body></SOAP-ENV:Envelope>';
    dbms_output.put_line('Length of Request:' || length(request_env));
    dbms_output.put_line ('Request: ' || request_env);
    http_req := utl_http.begin_request('http://www50.brinkster.com/vbfacileinpt/np.asmx','POST', utl_http.HTTP_VERSION_1_1);
    utl_http.set_header(http_req, 'Content-Type', 'text/xml; charset=utf-8');
    utl_http.set_header(http_req, 'Content-Length', length(request_env));
    utl_http.set_header(http_req, 'SOAPAction', '"http://microsoft.com/webservices/GetPrimeNumbers"');
    utl_http.write_text(http_req, request_env);
    dbms_output.put_line('');
    http_resp := utl_http.get_response(http_req);
    dbms_output.put_line('Response Received');
    dbms_output.put_line('--------------------------');
    dbms_output.put_line ( 'Status code: ' || http_resp.status_code );
    dbms_output.put_line ( 'Reason phrase: ' || http_resp.reason_phrase );
    utl_http.read_text(http_resp, response_env);
    dbms_output.put_line('Response: ');
    dbms_output.put_line(response_env);
    utl_http.end_response(http_resp);
    end test_ws_2;
    Otherwice for testing url, i recommand you to use that function: Re: Error using UTL_HTTP over HTTPS
    it's a verry helpful function when you have an error.
    wrote:
    When testing using UTL_HTTP, you MUST ensure that you open a new session after importing the SSL certificates into your Wallet,
    as I've learned (the hard way) that existing sessions point to the wallet contents that were present when the session was opened.
    If you don't realise/know this, it can cause a lot of additional frustration during testing, when you keep getting the ORA-29024 exception AFTER
    you've imported the SSL certificates................. ;) 3. i think you can use that after the begin_request but not sure :
    UTL_HTTP.set_authentication(r => http_req,
    username => ,
    password => ,
    scheme => ,
    for_proxy => );
    Edited by: Malebodja on Oct 22, 2009 6:53 AM
    Edited by: Malebodja on Oct 22, 2009 6:55 AM

  • NIO non-blocking i/o- Any advantages for UDP server??

    Hi,
    I am developing a classic UDP-based server which serves hundreds of clients simultaneously. After receiving a simple request from a client, the server replies with a simple response (messages are no larger than 50 bytes).
    What, if any non-blocking-related advantages would there be in using nio? Specifically, if I used select() without turning on non-blocking on the data channel, what do I lose?
    The architecture consists of only one socket for responding to client requests. It uses receive() and send(), not read()/write()/connect().
    Thanks in advance,
    Dan.

    >>
    What, if any non-blocking-related advantageswould
    there be in using nio? Specifically, if I used
    select() without turning on non-blocking on thedata
    channel, what do I lose?You cannot do this. The runtime will throw an
    IllegalBlockingModeException when you tried to
    register it.
    So in order to use select(), your registered channels must
    be in non-blocking mode? Why? That's just the way it is?
    So to conclude, using non-blocking mode provides no real advantage for
    my application. It is only required or else I would not be able to use
    select(), right? If so, what is so good about nio? Can you give an example that is similar to my application which would benefit from the non-blocking characteristic of nio?
    Thanks for your help so far...
    Daniel.
    >>
    The architecture consists of only one socket for
    responding to client requests. It uses receive()and
    send(), not read()/write()/connect().If you are only reading from one socket there are
    theoretical advantages to servicing requests on more
    than one thread, but you would not use non-blocking
    mode to do this.
    However I think some operating systems have
    performance problems when doing this. Look at this
    article under accept serialization:
    http://httpd.apache.org/docs/misc/perf-tuning.html
    The same problems may apply to multi-thread udp socket
    readers.

  • Are the experts wrong about non-blocking SocketChannels?

    Everyone says to use the new SocketChannel and Selector for "highly scalable" server applications. So I ran a couple of tests using non-blocking (via Selector) and thread-per-connection SocketChannels.
    The Selector version consumes 8x more cpu than the thread-per-connecton version!
    Using JDK 1.4.1 FCS on Win2K, with 1000 socket connections each sending 1k bytes per second, the Selector version was consuming 40% cpu with 10 threads; the thread-per-connection version (using blocking SocketChannels) was only consuming about 5% cpu with 1009 threads.
    So, are the experts wrong? Is there a performance problem when number of SocketChannels exceed a certain threshold?
    For anyone interested, here's the source code:
    Non-Blocking Server using Selector
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    import java.nio.channels.FileChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class Server4 implements Runnable
    private static int port = 80;
    public static void main(String args[]) throws Exception
    Server4 server = new Server4();
    Thread thread = new Thread(server);
    thread.setDaemon(true);
    thread.start();
    thread.join();
    public Server4() throws IOException
    ServerSocketChannel server = ServerSocketChannel.open();
    InetSocketAddress isa = new InetSocketAddress(port);
    server.configureBlocking(false);
    server.socket().bind(isa);
    m_selector = Selector.open();
    server.register(m_selector, SelectionKey.OP_ACCEPT);
    Charset utf8 = Charset.forName("UTF-8");
    m_decoder = utf8.newDecoder();
    m_encoder = utf8.newEncoder();
    public void run()
    int count = 0;
    try
    ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
    //FileOutputStream fos = new FileOutputStream("server4.dat");
    //FileChannel fc = fos.getChannel();
    while (m_selector.select() > 0)
    Set keys = m_selector.selectedKeys();
    for (Iterator itr = keys.iterator(); itr.hasNext(); )
    SelectionKey key = (SelectionKey) itr.next();
    itr.remove();
    if (key.isAcceptable())
    System.out.println("accept: " + (++count));
    ServerSocketChannel server
    = (ServerSocketChannel) key.channel();
    SocketChannel channel = server.accept();
    channel.configureBlocking(false);
    channel.register(m_selector, SelectionKey.OP_READ);
    else
    SocketChannel channel = null;
    try
    if (key.isReadable())
    channel = (SocketChannel) key.channel();
    int bytes = channel.read(buffer);
    if (bytes <= 0) // Linux does not throw IOException
    channel.close(); // will also cancel key
    System.out.println("connection closed " + count);
    else
    buffer.flip();
    //fc.write(buffer);
    buffer.clear();
    catch (IOException ioe) // connection closed by client
    System.out.println("readable: " + ioe.getMessage());
    sm_logger.log(Level.INFO, ioe.getMessage(), ioe);
    Throwable cause = ioe.getCause();
    if (cause != null)
    System.out.println("cause: "
    + cause.getClass().getName()
    + ": " + cause.getMessage());
    channel.close(); // will also cancel key
    --count;
    catch (IOException e)
    System.out.println("run: " + e.getMessage());
    sm_logger.log(Level.SEVERE, e.getMessage(), e);
    catch (Exception e)
    System.out.println("run: " + e.getMessage());
    sm_logger.log(Level.SEVERE, e.getMessage(), e);
    private Selector m_selector;
    private CharsetDecoder m_decoder;
    private CharsetEncoder m_encoder;
    private static Logger sm_logger = Logger.getLogger("Server");
    Thread-Per-Connection Server
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    import java.nio.channels.FileChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class MultiThreadServer implements Runnable
    private static int port = 80;
    public static void main(String[] args) throws Exception
    ServerSocketChannel server = ServerSocketChannel.open();
    InetSocketAddress isa = new InetSocketAddress(port);
    server.socket().bind(isa);
    int count = 0;
    while (true)
    SocketChannel channel = server.accept();
    System.out.println("accept: " + (++count));
    MultiThreadServer worker = new MultiThreadServer(channel);
    Thread thread = new Thread(worker);
    thread.setDaemon(true);
    thread.start();
    public MultiThreadServer(SocketChannel channel) throws IOException
    m_channel = channel;
    public void run()
    ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
    int bytes = 0;
    try
    while ((bytes = m_channel.read(buffer)) > 0)
    buffer.flip();
    // process buffer
    buffer.clear();
    System.out.println("connection closed");
    m_channel.close();
    catch (IOException e)
    System.out.println("run: " + e.getMessage());
    sm_logger.log(Level.SEVERE, e.getMessage(), e);
    catch (Exception e)
    System.out.println("run: " + e.getMessage());
    sm_logger.log(Level.SEVERE, e.getMessage(), e);
    private SocketChannel m_channel;
    private static Logger sm_logger = Logger.getLogger("MultiThreadServer");
    Client
    import java.io.*;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class MultiClient implements Runnable
    public static void main(String[] args) throws Exception
    if (args.length < 1)
    System.out.println("usage: java MultiClient number [host]");
    System.exit(1);
    int number = Integer.parseInt(args[0]);
    String host = (args.length == 2) ? args[1] : "localhost" ;
    Thread[] threads = new Thread [number];
    InetSocketAddress address = new InetSocketAddress(host, 80);
    for (int i = 0; i < number; i++)
    MultiClient client = new MultiClient(address, Integer.toString(i));
    threads[i] = new Thread(client);
    threads.setDaemon(true);
    for (int i = 0; i < number; i++)
    threads[i].start();
    for (int i = 0; i < number; i++)
    threads[i].join();
    public MultiClient(InetSocketAddress address, String id)
    throws InterruptedException, IOException
    m_id = id;
    Charset charset = Charset.forName("UTF-8");
    m_decoder = charset.newDecoder();
    m_encoder = charset.newEncoder();
    m_channel = SocketChannel.open();
    m_channel.connect(address);
    if (id.equals("0"))
    Socket socket = m_channel.socket();
    System.out.println("SO_SNDBUF=" + socket.getSendBufferSize()
    + ",SO_TIMEOUT=" + socket.getSoTimeout()
    + ",SO_KEEPALIVE=" + socket.getKeepAlive());
    byte[] buf = new byte [1024]; // bufsize = 1K
    Arrays.fill(buf, (byte) m_id.charAt(0));
    m_buffer = ByteBuffer.allocateDirect(1024);
    m_buffer.put(buf);
    m_buffer.flip();
    Thread.currentThread().sleep(50L);
    public void run()
    System.out.print(m_id);
    try
    while (true)
    m_channel.write(m_buffer);
    m_buffer.rewind();
    Thread.currentThread().sleep(1000L);
    catch (IOException ioe)
    ioe.printStackTrace();
    catch (InterruptedException ie)
    System.err.println(ie.toString());
    private String m_id;
    private CharsetEncoder m_encoder;
    private CharsetDecoder m_decoder;
    private SocketChannel m_channel;
    private ByteBuffer m_buffer;

    {This is a crosspost. I posted this earlier today at http://forum.java.sun.com/thread.jsp?forum=4&thread=319822 before I stumbled on a search phrase that located this older thread.
    All follow-ups should be on haam's thread instead of mine. The important point below is that NIO select() behavior (vs. threading IO)  is [b]worse under Windows but better under Solaris. This seems fundamentally broken. }
    My company sells a scalable multi-user server platform built on Java 2.
    It runs under Java 1.3.1 (and 1.4.0 windows) using multiple threads for communications, and 1.4.x (unix) using NIO. We were happy to see that 1.4.1 (windows) fixed the problem drastically limiting the number of selectable ports. :-)
    The bad news is that whatever the VM is doing "under the sheets" to fix the problem seems to perform very poorly in terms of CPU:
    I compared connecting 500 simulated users to a Solaris 8 and a Win2K box. These users were in 25 chat rooms, each sending a chat message every 30 seconds. (There was plenty of memory on each machine. There was no swapping in either case. Clock/CPU type doesn't matter as this isn't about comparing a machine to a machine, but different load characteristics -within- a machine environment.)
                    Threaded IO      NIO/Select
    Solaris 1.4.1     20-30%           15- 20%
    Windows 1.4.1     40-50%           95-100%Numbers are % of CPU as reported by 'top' and the Win2K task manager.
    Both platforms showed the expected significant improvement in memory usage when moving from standard threaded IO to NIO.
    Strangely, the Windows implementation of the VM showed a significant (and unexpected) degradation of NIO performance vs. the threaded model, whereas the Solaris VM behaved as expected: NIO outperformed threaded IO.
    Our best guess is that the Selector fix in 1.4.1 is implemented in some cpu-intensive way; perhaps polling. As a result, we still can't use NIO for Wintel boxes running our server. :-( To us, Selector
    is still broken.
    Has anyone else seen results like this? Have we missed some configuration parameter that will fix this?
    I thought the big upside of using select() was supposed to be performance. :-P
    F. Randall Farmer
    State Software, Inc.
    http://www.statesoftware.com

  • Non-blocking Vectored read from SocketChannel fails

    Hi.
    Please look at the code example:
    ByteBuffer tmp1 = ByteBuffer.allocate(500);
    ByteBuffer tmp2 = ByteBuffer.allocate(500);
    ByteBuffer[] tmp = {tmp1, tmp2};
    while ((count = socketChannel.read(tmp)) > 0) {
    + "bytes.");
    When I run this code, (using non-blocking socket channel), the first buffer is read ok, but on the second round of the while loop, I get an IOException, saying: "a non blocking socket operation could not be completed immediately".
    If I put 'tmp1' instead of 'tmp' in the read(), (i.e - use a normal buffer), the read successfully finishes.
    Why?
    I found nothing in the documentation, and in the 'Java NIO' book (Ron Hitchens).
    Help?
    Thanks.

    Please ignore the + "bytes."); inside the while.

Maybe you are looking for

  • I can't load instructor image in itunes u course manager

    I am trying to set up my instructor profile but when I try and load my pic (400 x 400) it just hangs and I cannot go any further

  • Xcode 4.4 autosave in Mountain Lion

    Unless I am missing something Xcode 4.4. does not honor the newly Ask to Keep Changes When Closing Document (aka autosave/revert feature) in Preferences > General. However it works for things like Textedit and Preview.  Does anyone know if it works o

  • How to get iOS 5.0 loaded on Mac iTunes?

    I am unable to get 5.0, iTunes,  says it is up to date with 4.2.1. My iPad updated to 5.0, but can't get 3G iPhone updated!  I don't know why laptop doesn't automatically update itself to 5.0. I tried 'check for available downloads'. Not computer sav

  • Trying to Deploy either a .cmd or .bat file to update a registry Entry but not working

    Hello. I'm trying to deploy either a .cmd or .bat file to a few computers to update the registry and When I run the .cmd or .bat on the pc manually it works just fine. However when I create an application and try to deploy to the computers I keep get

  • Will not sign me in to update software E63

    Right, here goes. Using this phone for the first time today. Put my sim card in, everything worked fine for a couple of hours. Then, no text messages I was sending were going through. After five minutes I receive the error message, 'unable to send me