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

📄 protocol.java

📁 J2me唆哈的代码
💻 JAVA
字号:
/*
 * Created on 2005-8-19 by pcy
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.booqio.emulator.io.socket;

import javax.microedition.io.*;

import a.a.a.midp.io.*;



import java.io.*;
import java.net.*;
/**
 * @author pcy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Protocol extends NetworkConnectionBase implements SocketConnection {

    protected static int bufferSize=4096;
    
    java.net.Socket instance;
    
    /** Hostname */
    private String host;

    /** TCP port */
    private int port;
    private InputStream is;
    private OutputStream os;
    private boolean outputShutdown;
    /**
     * 
     */
    public Protocol() {
        super(bufferSize);
        // TODO Auto-generated constructor stub
    }
    
    public Protocol(java.net.Socket s){
        super(bufferSize);
        instance=s;
        this.connectionOpen=true;
    }

    
    public Connection openPrim(String name, int mode, boolean timeouts)
    throws IOException {

        HttpUrl url;
        if (name.charAt(0) != '/' || name.charAt(1) != '/') {
            throw new IllegalArgumentException(
                      "Protocol must start with \"//\"");
        }
    
        url = new HttpUrl("socket", name); // parse name into host and port
    
        /*
         * Since we reused the HttpUrl parser, we must make sure that
         * there was nothing past the authority in the URL.
         */
        if (url.path != null || url.query != null || url.fragment != null) {
            throw new IllegalArgumentException("Malformed address");
        }
    
        host = url.host;
        port = url.port;
        
        /*
         * If 'host' == null then we are a server endpoint at
         * port 'port'.
         */
        //System.out.println("Host: "+host+":"+port);
        if (host != null) {
            // this will call the connect method which uses the host and port
            return super.openPrim(name, mode, timeouts);
        }
    
        // We allow "socket://:nnnn" to mean an inbound TCP server socket.
        com.booqio.emulator.io.serversocket.Socket con = new com.booqio.emulator.io.serversocket.Socket();
        con.open(port);
        return con;
    }
    
    public void connect(String name, int mode, boolean timeouts)
    throws IOException {

        //byte[] szHost;
    
        //verifyPermissionCheck();
    
        /*
         * The host and port were set by overridding the openPrim method of
         * our super class.
         */
    	
        if (port < 0) {
            throw new IllegalArgumentException("Missing port number");
        }
    
        //szHost = Util.toCString(host);
        open0(host,port);
        //registerCleanup();
    }
    
    public void disconnect() throws IOException {

        if (!outputShutdown) {
            shutdownOutput0();
        }
        close0();
    }
    
    public boolean isClosed(){
        return instance.isClosed();
    }
    
    
    protected void closeOutputStream() throws IOException {
        /*
         * Shutdown the output gracefully closes the sending side of the 
         * TCP connection by sending all pending data and the FIN flag.
         */
        shutdownOutput0();
        outputShutdown = true;
        super.closeOutputStream();
    }
    
    
    protected int nonBufferedRead(byte b[], int off, int len)
    throws IOException {

        int bytesRead;
        if(is==null){
        	is=instance.getInputStream();
        }
        for (;;) {
            try {
                bytesRead = is.read(b, off, len);
            } finally {
                if (iStreams == 0) {
                    throw new InterruptedIOException("Stream closed");
                }
            }
    
            if (bytesRead == -1) {
                eof = true;
                return -1;
            }
    
            if (bytesRead != 0) {
                return bytesRead;
            }
    
            /* Wait a while for I/O to become ready */
            //GeneralBase.iowait(); 
        }
    }

    /*
    public void open(int handle) {
        this.handle = handle;

        try {
            connectionOpen = true;
            checkForPermission(getAddress());
        } catch (Exception e) {
            connectionOpen = false;

            if (e instanceof IOException) {
                e = new SecurityException("Unknown TCP client");
            }

            try {
                close0();
            } catch (IOException ioe) {
                // ignore
            }

            throw (RuntimeException)e;
        }
        
        registerCleanup();
    }
*/
    
    public int available() throws IOException {
        if (count > 0) {
            /*
             * The next read will only return the bytes in the buffer,
             * so only return the number of bytes in the buffer.
             * While available can return a number less than than the next
             * read will get, it should not return more.
             */
            return count;
        }

        // The buffer is empty, so the next read will go directly to native
        return available0();
    }

    public int writeBytes(byte b[], int off, int len) throws IOException {
        return write0(b, off, len);
    }


    private void checkOption(byte option) 
        throws IllegalArgumentException {
        if (option == SocketConnection.KEEPALIVE 
            || option == SocketConnection.LINGER 
            || option == SocketConnection.SNDBUF 
            || option == SocketConnection.RCVBUF 
            || option == SocketConnection.DELAY) {
            return;
        }
        throw new IllegalArgumentException("Unsupported Socket Option");
        
    }


    public void setSocketOption(byte option,  int value) 
    throws IllegalArgumentException, IOException {
        checkOption(option);
        if (value < 0) {
            throw new IllegalArgumentException("Unsupported Socket Option");
        }
        ensureOpen();
    
        setSockOpt0(option, value);
    }
    
    public  int getSocketOption(byte option) 
    throws IllegalArgumentException, IOException  {
        checkOption(option);
        ensureOpen();
        return getSockOpt0(option);
    }
 
    public  String getLocalAddress() throws IOException {
        ensureOpen();
        return getHost0(true);
    }


    public  int  getLocalPort()  throws IOException {
        ensureOpen();
        return getPort0(true); 
    }


    public  String getAddress() throws IOException {
        ensureOpen();
        return getHost0(false);
    }

    public  int  getPort() throws IOException {
        ensureOpen();
        return getPort0(false); 
    }


    private void open0(String name, int port) throws IOException{
        instance=new Socket(name,port);
        instance.setTcpNoDelay(true);
    }


    /*private int read0(byte b[], int off, int len) throws IOException{
        return instance.getInputStream().read(b,off,len);
    }*/

    private int write0(byte b[], int off, int len) throws IOException{
        if(os==null){
        	os=instance.getOutputStream();
        }
    	os.write(b,off,len);
        return len;
    }


    private int available0() throws IOException{
    	if(is==null){
    		is=instance.getInputStream();
    	}
        return is.available();
    }


    private void close0() throws IOException{
    	if(!instance.isInputShutdown()){
    		instance.shutdownInput();
    	}
    	if(!instance.isOutputShutdown()){
    		instance.shutdownOutput();
    	}
        instance.close();
    }


    private String  getHost0(boolean local){
        if(local){
            return instance.getLocalAddress().getHostName();
        }else{
            return instance.getInetAddress().getHostName();
        }
    }


    private int  getPort0(boolean local){
        if(local){
            return instance.getLocalPort();
        }else{
            return instance.getPort();
        }
    }
    

    private int  getSockOpt0(int option){
        return 0;
    }


    private void  setSockOpt0(int option, int value){
        
    }


    private void shutdownOutput0()throws IOException{
        //instance.getOutputStream().close();
        os.close();
    }
}

⌨️ 快捷键说明

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