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

📄 hsocket.java~259~

📁 jwap 协议 udp 可以用于手机通讯
💻 JAVA~259~
📖 第 1 页 / 共 2 页
字号:
            responseCode = Integer.parseInt(message.substring(mark + 1,
                    mark += 4));
            responseMessage = message.substring(mark, message.length()).trim();
            /* if(responseCode==200)
             {
                 upperLayer.tr_download(responseCode);
             }*/
            // 应答状态码和处理请读者添加
            switch (responseCode) {
            case 400:
                System.out.println("错误请求");
                throw new IOException("错误请求");
            case 404:
                System.out.println(getURLFormat(target));
                throw new FileNotFoundException(getURLFormat(target));
            case 503:
                System.out.println("服务器不可用");
                throw new IOException("服务器不可用");
            }

            if (word == -1) {
                System.out.println("信息接收异常终止");
                throw new ProtocolException("信息接收异常终止");
            }

            int symbol = -1;
            count = 0;
            // 解析元信息
            while (word != '\r' && word != '\n' && word > -1) {
                if (word == '\t') {
                    word = 32;
                }
                if (count == data.length) {
                    data = addCapacity(data);
                }
                data[count++] = (byte) word;
                parseLine: {
                    while ((symbol = Tcpinput.read()) > -1) {
                        switch (symbol) {
                        case '\t':
                            symbol = 32;
                            break;
                        case '\r':
                        case '\n':
                            word = Tcpinput.read();
                            if (symbol == '\r' && word == '\n') {
                                word = Tcpinput.read();
                                if (word == '\r') {
                                    word = Tcpinput.read();
                                }
                            }
                            if (word == '\r' || word == '\n' || word > 32) {
                                break parseLine;
                            }
                            symbol = 32;
                            break;
                        }
                        if (count == data.length) {
                            data = addCapacity(data);
                        }
                        data[count++] = (byte) symbol;
                    }
                    word = -1;
                }
                message = new String(data, 0, count);
                logger.error(message);
                mark = message.indexOf(':');
                String key = null;
                if (mark > 0) {
                    key = message.substring(0, mark);
                }
                mark++;
                while (mark < message.length() && message.charAt(mark) <= 32) {
                    mark++;
                }
                String value = message.substring(mark, message.length());
                String str = key.toLowerCase();
                if (str.equals("content-length")) {
                    totlelen = Integer.parseInt(value.trim());
                }
                if (str.equals("connection")) {
                    String tval=value.toLowerCase();
                    if(tval.equals("close"))
                    responseCode=-1;
                }

                header.put(key, value);
                count = 0;
            }

            // 获得正文数据
            byte databuf[] = new byte[1024];
            while (((word = Tcpinput.read()) != -1)) {
                if (count == data.length) {
                    data = addCapacity(data);
                }

                data[count++] = (byte) word;
                if (count >= totlelen) {
                    break;
                }

                //markflg.ReceiveBag();
                //data = temp;//addCapacitybuf(data, databuf);
            }

//=======================================================================
            /* if (word > 0) {
                 if(icount==1)
                 {
                   System.arraycopy(databuf, 0, data, 0, word);
                    System.out.println(icount + " 接收到 1024 字节");
                   icount++;
                 }
                   else
                   {
                       int len = data.length;
                       byte temp[] = new byte[data.length + word];

                       System.out.println(icount + " 接收到 1024 字节");
                       icount++;
                       System.arraycopy(data, 0, temp, 0, data.length);
                       System.arraycopy(databuf, 0, temp, data.length, word);
                       data = temp;

                   }
                 markflg.ReceiveBag();

                 //data = temp;//addCapacitybuf(data, databuf);
                 count=data.length;
                  if(count>=totlelen)
                  {
                      break;
                  }
             }
                         }*/
            //==================================================================================

            if (count > 0) {
                upperLayer.tr_download(responseCode);

                byteStream = new ByteArrayInputStream(data, 0, count);
            }
            // data = null;
        } catch (IOException ex) {
            responseCode = -1;
            String str = "下载失败";
            byteStream = new ByteArrayInputStream(str.getBytes());
            System.out.println(ex.getMessage());
        }
        //upperLayer.tr_downok(outdate);
        try {
            if (responseCode == -1) {
                int len = data.length;
                if (len > 0) {
                    byteStream = new ByteArrayInputStream(data, 0, len);
                } else {
                    responseCode = -1;
                    String str = "下载失败";
                    byteStream = new ByteArrayInputStream(str.getBytes());
                }
            }
            closeServer();
        } catch (Exception ex1) {
            responseCode = -1;
        }

        finally {
            data = null;
            System.out.println(responseCode);
            System.out.println(responseMessage);
            //System.out.println(responseCode);

        }
    }

    protected void closeServer() throws IOException {
        if (TcpSocket == null) {
            return;
        }
        try {
            TcpSocket.close();
            Tcpinput.close();
            Tcpoutput.close();
        } catch (IOException i) {
            //throw i;
            System.exit(1);
        }
        TcpSocket = null;
        Tcpinput = null;
        Tcpoutput = null;
    }

    private byte[] addCapacity(byte rece[]) {
        byte temp[] = new byte[rece.length + 1024];
        System.out.println(icount + " 接收到 1024 字节");
        icount++;
        System.arraycopy(rece, 0, temp, 0, rece.length);
        markflg.ReceiveBag();
        return temp;
    }

    private byte[] addCapacitybuf(byte rece[], byte dat[]) {
        byte temp[] = new byte[rece.length + 1024];
        temp = rece;
        System.out.println(icount + " 接收到 1024 字节");
        icount++;
        System.arraycopy(rece, 0, temp, 0, rece.length);
        System.arraycopy(dat, 0, temp, rece.length, 1024);
        markflg.ReceiveBag();
        return temp;
    }


    public String getResponseMessage() {
        return responseMessage;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public String getServerVersion() {
        return serverVersion;
    }

    public InputStream getInputStream() {
        return byteStream;
    }

    public synchronized String getHeaderKey(int i) {
        if (i >= header.size()) {
            return null;
        }
        Enumeration enum1 = header.propertyNames();
        String key = null;
        for (int j = 0; j <= i; j++) {
            key = (String) enum1.nextElement();
        }
        return key;
    }

    public synchronized String getHeaderValue(int i) {
        if (i >= header.size()) {
            return null;
        }
        return header.getProperty(getHeaderKey(i));
    }

    public synchronized String getHeaderValue(String key) {
        return header.getProperty(key);
    }

    protected String getBaseHeads() {
        return baseheader;

    }

    protected void setBaseHeads(String headerstr) {
        baseheader = headerstr;
    }

    /*
     * POST方法是向服务器传送数据,以便服务器做出相应的处理。例如网页上常用的
     * 提交表格。
     */
    public int POST(String url) {
        try {
            checkHTTP(url);
            String str = "hello word";
            String cmd = "POST " + getURLFormat(target) + "HTTP/1.1\r\n" +
                         getBaseHeads();
            cmd += "Content-type: " + this.contentType + "\r\n";
            cmd += "Content-length: " + this.payload.length + "\r\n\r\n";
            //cmd += this.payload + "\r\n";
            sendData(cmd);
            receiveSendBack();
        } catch (Exception p) {
            System.out.println("POST:"+p.getMessage());
            return -1;
        }

        return 0;

    }


    /* GET方法根据URL,会请求文件、数据库查询结果、程序运行结果等多种内容 */
    public int GET(String url) {
        // streamcreat();
        try {
            checkHTTP(url);
            String cmd = "GET " + getURLFormat(target) + " HTTP/1.1\r\n"
                         + getBaseHeads() + "\r\n";

            sendMessage(cmd);
            receiveMessage();

        } catch (ProtocolException p) {
            p.printStackTrace();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

        return responseCode;
    }

    protected void checkHTTP(String url) throws ProtocolException {
        try {
            URL target = new URL(url);
            if (target == null ||
                !target.getProtocol().toUpperCase().equals("HTTP")) {
                throw new ProtocolException("这不是HTTP协议");
            }
            this.target = target;
        } catch (MalformedURLException m) {
            throw new ProtocolException("协议格式错误");
        }
    }

    public void start()


    {
        runner = new Thread(this);
        runner.start();
    }


    public void stop() {
        if (runner != null) {
            runner.stop();
            runner = null;
        }
    }

    public void run() {

        int i = 0;
        int ret = -1;
        while (true) {
            if (get_post == 1) {

                ret = POST(geturl);
                if (ret == -1) {
                    runner = null;
                   break;
                } else {

                    int len = byteStream.available();

                    byte outdata[] = new byte[len + 1];
                    try {
                        byteStream.read(outdata);
                    } catch (IOException ex) {
                        ret = -1;

                    }

                    upperLayer.tr_result(ret, outdata);
                    break;

                }

            } else {

                ret = GET(geturl);

                if (ret == -1) {
                    runner = null;
                    break;
                } else {
                    int len = byteStream.available();

                    byte outdata[] = new byte[len + 1];
                    try {
                        byteStream.read(outdata);
                    } catch (IOException ex) {
                        ret = -1;

                    }

                    upperLayer.tr_result(ret, outdata);
                    runner = null;
                    break;
                    //i++;
                }

            }
           /* if (i > 2) {
                break;
            }*/
        }

        /* try {
             this.closeServer();
         } catch (IOException ex1) {
         }*/
    }

    /**
     * Seturl
     *
     * @param m_url String
     */
    public void Seturl(String m_url) {
        if (m_url.equals("")) {
            System.out.println("连接地址不能为空");
            System.exit(1); ;
        }
        geturl = m_url;
    }

    public void SetGet_Post(int flg) {
        get_post = flg;
    }

    public void SetPostData(byte[] paydata) {
        this.payload = paydata;
    }

    public void SetcontentType(String cntType) {
        this.contentType = cntType;
    }


}

⌨️ 快捷键说明

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