⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httptransport.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
        return publicAddress;
    }
    
    public boolean isConnectionOriented() {
        return false;
    }
    
    /**
     * Returns true if the endpoint protocol can be used by the EndpointRouter
     *
     * @return boolean true if the protocol can be used by the EndpointRouter
     */
    public boolean allowRouting() {
	return true;
    }

    public synchronized String getProxy() {
        return proxyName;
    }
    
    public synchronized Vector getRouters() {
        return routers;
    }
    
    public synchronized String getServer() {
        return serverName;
    }
    
    public synchronized boolean doesPropagate() {
        return false;
    }
    
    private String getHttpHeader( String entity ) {
        int firstCRLFCRLF = entity.indexOf( "\r\n\r\n" ) + 4;
        int firstLFLF = entity.indexOf( "\n\n" ) + 2;
        
        firstCRLFCRLF = (firstCRLFCRLF < 4) ? Integer.MAX_VALUE : firstCRLFCRLF;
        firstLFLF = (firstLFLF < 2) ? Integer.MAX_VALUE : firstLFLF;
        
        int endOfHeader = Math.min( firstCRLFCRLF, firstLFLF );
        
        if( Integer.MAX_VALUE != endOfHeader )
            return entity.substring( 0, endOfHeader );
        else
            return null;
    }
    
    /**
     *  This is the method which handles incoming connections. It is called
     *  from an instance of IncomingUnicastThread.
     **/
    public void runReceive(Socket inputSocket) {
        // XXX: Note that this implementation heavely
        // uses Strings to parse the request. A more efficient
        // manner would be manipulate directely the array of
        // bytes. The reason for using strings is that it helps
        // debugging. Once the code will be stable enough, this
        // part will be revisited to be more efficient.
        // lomax@jxta.org
        
        final String htmlstart = "<HTML>\n";
        final String htmlend = "\n</HTML>\n";
        
        InputStream inputStream = null;
        OutputStream outputStream = null;
        
        try {
            inputStream = inputSocket.getInputStream();
            
            if( null == inputStream ) {
                closeSocket( inputSocket, inputStream, outputStream );
                if (LOG.isEnabledFor(Priority.WARN)) LOG.warn( "Could not get input stream from socket" );
                return;
            }
            
            HttpMessage outgoingMessage = null;
            
            String packet = getResult(inputStream, false);
            
            if (packet == null) {
                if (LOG.isEnabledFor(Priority.WARN)) LOG.warn("null message - discard");
                closeSocket( inputSocket, inputStream, outputStream );
                return;
            }
            
            String httpHeader = getHttpHeader( packet );
            
            // XXX 20010913 bondolo@jxta.org need more error handling here
            int index = httpHeader.indexOf(" ");
            String cmd = httpHeader.substring(0, index );
            String uri = httpHeader.substring(index + 1, httpHeader.indexOf(" HTTP") );
            
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Incoming client request : " + cmd + " " + uri );
            
            // Handle GET, figure out what the client wants
            if (cmd.equals("GET")) {
                int ii = 0;
                String type = null;
                
                index = uri.indexOf("/reg/");
                if (index >= 0) {
                    type = HttpTransport.Register;
                    ii = index;
                }
                index = uri.indexOf("/rec/");
                if (index >= 0) {
                    type = HttpTransport.Receive;
                    ii = index;
                }
                index = uri.indexOf("/blk/");
                if (index >= 0) {
                    type = HttpTransport.BlockingReceive;
                    ii = index;
                }
                index = uri.indexOf("/snd/");
                if (index >= 0) {
                    type = HttpTransport.Send;
                    ii = index;
                }
                index = uri.indexOf("/ack/");
                if (index >= 0) {
                    type = HttpTransport.Ping;
                    ii = index;
                }
                
                if (type == null) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Unrecognized command in request" );
                    // FIXME 20010913 bondolo@jxta.org should generate a 400 here
                    closeSocket( inputSocket, inputStream, outputStream );
                    return;
                }
                String param = uri.substring(ii + 5);
                
                if (param.indexOf("/") >= 0) {
                    param = param.substring(0, param.length() - 1);
                }
                
                if (type.equals(Register)) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Registering remote peer");
                    outgoingMessage = register(param);
                }
                
                if (type.equals(Receive)) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Remote peer polls messages");
                    outgoingMessage = processOutgoing(param, false, inputSocket, inputStream);
                }
                
                if (type.equals(BlockingReceive)) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Remote peer polls messages - blocking");
                    outgoingMessage = processOutgoing(param, true, inputSocket, inputStream);
                }
                
                if (type.equals(Ping)) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Processing ping");
                    outgoingMessage = processPing();
                }
            }
            
            // If its a PUT or POST receive the message
            if (cmd.equals("PUT") || cmd.equals("POST")) {
                
                // Strip <HTML> tags
                int indexFirst = packet.indexOf( htmlstart, httpHeader.length() );
                int indexLast = packet.lastIndexOf( htmlend );
                
                if ((indexFirst >= 0) && (indexLast > 0)) {
                    packet = packet.substring(
                    indexFirst + htmlstart.length(), indexLast);
                } else {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Invalid message len=" + packet.length() +
                    " indexFirst=" + indexFirst + " indexLast=" + indexLast );
                    // FIXME 20010913 bondolo@jxta.org should generate a 400 here
                    closeSocket( inputSocket, inputStream, outputStream );
                    return;
                }
                
                outgoingMessage = processIncoming(packet);
            }
            
            // If there is a response, send it.
            if (outgoingMessage != null) {
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Sending response for : " + cmd + " " + uri );
                
                outputStream = inputSocket.getOutputStream();
                
                if (null == outputStream ) {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("HTTP: outputstream is null, message discarded");
                    closeSocket( inputSocket, inputStream, outputStream );
                    return;
                }
                
                byte [] body = outgoingMessage.getBytes();
                
                Vector buffers = new Vector();
                buffers.addElement(body);
                sendResponse(outputStream, buffers, body.length);
                
                closeSocket( inputSocket, inputStream, outputStream );
            } else {
                // someone else is going to send the response. we don't
                // send anything or close the socket.
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Still need response for " +
                inputSocket.getInetAddress().getHostAddress() + ":" +
                inputSocket.getPort() );
                return;
            }
            
        } catch (Exception e) {
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("runReceive : Aborting connection to  " +
            inputSocket.getInetAddress().getHostAddress() + ":" +
            inputSocket.getPort(), e);
            closeSocket( inputSocket, inputStream, outputStream );
        }
    }
    
    /**
     *  Send a message
     *
     *  @param  url the destination server
     *  @param  buffers the data to send.
     *  @param  size    the size of the message in the buffers.
     *  @return boolean    true if message was sent otherwise false.
     **/
    public boolean sendHttpPUT( URL url, Enumeration buffers, long size )
    throws IOException {
        
        Socket socket = null;
        InputStream ip = null;
        OutputStream op = null;
        
        if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Client PUT  to " + url );
        
        socket = openSocket( url );
        
        if( null == socket ) {
            if (LOG.isEnabledFor(Priority.WARN)) LOG.warn( "failed to open socket. Message not sent." );
            return false;
        }
        
        // Builds HTTP header
        // Adding 16 to the size of the buffer is needed in order
        // to add the <HTML> and </HTML> tags.
        String hostName = url.getHost();
        int port = url.getPort();
        port = (-1 == port) ? 80 : port;
        
        String header = "POST " + url + " HTTP/1.1\r\n" +
        "Host: " + hostName + ":" + port + "\r\n" +
        "Content-Type: " + "application/octet-stream\r\n" +
        "Content-Length: " + (size + 16) + "\r\n" +
        "User-Agent: Jxta1.0\r\n\r\n";
        
        try {
            op = socket.getOutputStream();
            ip = socket.getInputStream();
            
            // Send the message
            
            op.write(header.getBytes());
            op.write("<HTML>\n".getBytes());
            while( buffers.hasMoreElements() ) {
                byte[] buffer = (byte[]) buffers.nextElement();
                op.write( buffer );
            }
            op.write("\n</HTML>\n".getBytes());
            op.flush();
            // XXX 20010917 bondolo@jxta.org We currently do nothing with response
            String response = getResult( ip, true );
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Client PUT Message sent" );
        } catch (Exception e) {
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("sendHttpPUT failed", e);
            
            return false;
        } finally {
            closeSocket( socket, ip, op );
        }
        
        return true;
    }
    
    /**
     * Make a polling request of the server and optionally wait for a reply
     *
     *  @param  url the server to contact.
     *  @param  type of connection to make
     *  @param wantReply  wait for a reply.
     **/
    private String sendHttpGET( URL url, int type, boolean wantReply )
    throws IOException {
        Socket socket = null;
        InputStream ip = null;
        OutputStream op = null;
        
        String reply = null;
        
        if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Client " +
        ((type == BlockingSend) ? "blocking" : "nonblocking") +
        " GET (" + (wantReply ? "with" : "w/o") + " reply) to " + url );
        
        try {
            socket = openSocket( url );
            
            // check if we got a connection
            if( null == socket ) {
                if (LOG.isEnabledFor(Priority.WARN)) LOG.warn( "Client GET failed to open socket. Message not sent." );
                return null;
            }
            
            op = socket.getOutputStream();
            ip = socket.getInputStream();
            
            String hostName = url.getHost();
            int port = url.getPort();
            port = (-1 == port) ? 80 : port;
            
            // Builds HTTP header
            String header = "GET " + url + " HTTP/1.1\r\n" +
            "Host: " + hostName + ":" + port + "\r\n" +
            "User-Agent: Jxta1.0\r\n" +
            "Content-Length: 0\r\n\r\n";
            
            // Send the empty message
            op.write(header.getBytes());
            //            op.write("<HTML>\n\n</HTML>\n".getBytes());
            op.flush();
            
            if( wantReply )
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Client GET Message sent, " +
                ((type == BlockingSend)? "blocking" : "polling") +

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -