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

📄 hsocket.java~264~

📁 jwap 协议 udp 可以用于手机通讯
💻 JAVA~264~
📖 第 1 页 / 共 2 页
字号:
package net.sourceforge.jwap.http;

/**
 * <p>Title: </p>
 *
 * <p>Description: nbpt</p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author chen
 * @version 1.0
 */
import java.io.*;
import java.net.*;
import java.util.*;

import net.sourceforge.jwap.util.*;
import net.sourceforge.jwap.wtp.markflg;

public class HSocket implements Runnable {

    static Logger logger = Logger.getLogger(HSocket.class);
    public Socket TcpSocket = null;
    public DataOutputStream Tcpoutput = null;
    public DataInputStream Tcpinput = null;
    protected URL target;
    private int responseCode = -1;
    private String responseMessage = "";
    private String serverVersion = "";
    protected ByteArrayInputStream byteStream;
    public String baseheader;
    private Properties header = new Properties();
    private Thread runner = null;
    public String geturl = "";
    public int icount = 1;
    public int get_post = 0;
    protected byte[] payload;
    private String contentType;

    /**
     * the upper Layer, modelling the session, WSP
     */
    private HttpUpperLayer upperLayer;

// remote port and address
    private int toPort = 80;
    private InetAddress toAddress;


    public HSocket() {
    }

    public HSocket(InetAddress mtoAddress, int mtoPort,
                   InetAddress localAddress,
                   int localPort, HttpUpperLayer m_upperLayer) {
        try {
            String str = mtoAddress.getHostAddress();
            toAddress = mtoAddress;
            toPort = mtoPort;
            TcpSocket = new Socket(mtoAddress.getHostAddress(), mtoPort);
            //TcpSocket = new Socket();
            Tcpoutput = new DataOutputStream(TcpSocket.getOutputStream());
            Tcpinput = new DataInputStream(TcpSocket.getInputStream());
            this.upperLayer = m_upperLayer;

        } catch (Exception ex) {
            TcpSocket = null;
        }

    }

    public void streamcreat() {
        if (TcpSocket == null) {
            try {
                TcpSocket = new Socket(toAddress.getHostAddress(), toPort);
            } catch (UnknownHostException ex3) {
            } catch (IOException ex3) {
            }
        }
        if (Tcpoutput != null) {
            try {
                Tcpoutput.close();
            } catch (IOException ex1) {
            }
            Tcpoutput = null;
        }
        if (Tcpinput != null) {
            try {
                Tcpinput.close();
            } catch (IOException ex2) {
            }
            Tcpinput = null;
        }

        try {
            Tcpoutput = new DataOutputStream(TcpSocket.getOutputStream());

            Tcpinput = new DataInputStream(TcpSocket.getInputStream());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public static void main(String[] args) {
        HSocket hsocket = new HSocket();
    }

    /**
     * Sconnect
     *
     * @param aLong long
     */
    public int Sconnect(InetAddress toAddress, int toPort, long timeout) {
        int ret = 8;
        return ret;
    }

    public int Sconnect() {
        int ret = 0;
        TcpSocket = null;
        try {
            TcpSocket = new Socket(toAddress.getHostAddress(), toPort);
            ret = 1;
        } catch (UnknownHostException ex) {
        } catch (IOException ex) {
        }
        //TcpSocket = new Socket();
        try {
            Tcpoutput = new DataOutputStream(TcpSocket.getOutputStream());
        } catch (IOException ex1) {
        }
        try {
            Tcpinput = new DataInputStream(TcpSocket.getInputStream());
        } catch (IOException ex2) {
        }

        return ret;
    }


    /**
     * SetSocketTimeout
     *
     * @param timeout long
     */
    public void SetSocketTimeout(int timeout) {
        try {
            TcpSocket.setSoTimeout(timeout);
        } catch (SocketException ex) {
        }
    }

    protected String getURLFormat(URL target) {
        String spec = "http://" + target.getHost();
        if (target.getPort() != -1) {
            spec += ":" + target.getPort();
        }
        return spec += target.getFile();
    }

    /* 向Web服务器传送数据 */
    protected void sendMessage(String data) throws IOException {
        Tcpoutput.write(data.getBytes(), 0, data.length());
        Tcpoutput.flush();
    }

    /* 向Web服务器传送数据 */
    protected void sendData(String data) throws IOException {
        Tcpoutput.write(data.getBytes(), 0, data.length());
        Tcpoutput.flush();
        int len = payload.length;
        // int count=(len/1024)+1;
        byte sendbuf[] = new byte[1024];
        int count = 0;
        int copylen = 0;
        for (int i = 0; i < len; ) {
            if ((len - i) < 1023) {
                copylen = len - i;
            } else {
                copylen = 1024;
            }
            System.arraycopy(payload, i, sendbuf, 0, copylen);
            i = i + 1024;
            Tcpoutput.write(sendbuf, 0, sendbuf.length);
            count++;
            System.out.println(count + " 发送" + copylen + " 个字节");
            Tcpoutput.flush();
        }
        //Tcpoutput.write(payload, 0, payload.length);
        String endstr = "\r\n";
        Tcpoutput.write(endstr.getBytes(), 0, endstr.length());
        Tcpoutput.flush();
    }

    protected void receiveSendBack() {
        byte data[] = new byte[1024];
        int count = 0;
        int word = -1;
        int totlelen = 0;

// 解析第一行Tcpinput
        System.out.println("请稍后,等待回应......");

        try {
            while ((word = Tcpinput.read()) != -1) {
                if (word == '\r' || word == '\n') {
                    word = Tcpinput.read();
                    if (word == '\n') {
                        word = Tcpinput.read();
                    }
                    break;
                }
                if (count == data.length) {
                    data = addCapacity(data);
                }
                data[count++] = (byte) word;
            }
            String message = new String(data, 0, count);
            logger.error(message);
            int mark = message.indexOf(32);
            serverVersion = message.substring(0, mark);
            while (mark < message.length() && message.charAt(mark + 1) == 32) {
                mark++;
            }
            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());
                }
                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);

        }
    }


    /* 接收来自Web服务器的数据 */
    protected void receiveMessage() {
        byte data[] = new byte[1024];
        int count = 0;
        int word = -1;
        int totlelen = 0;

// 解析第一行Tcpinput
        System.out.println("请稍后,正在下载中......");

        try {
            while ((word = Tcpinput.read()) != -1) {
                if (word == '\r' || word == '\n') {
                    word = Tcpinput.read();
                    if (word == '\n') {
                        word = Tcpinput.read();
                    }
                    break;
                }
                if (count == data.length) {
                    data = addCapacity(data);
                }
                data[count++] = (byte) word;
            }
            String message = new String(data, 0, count);
            logger.error(message);
            int mark = message.indexOf(32);
            serverVersion = message.substring(0, mark);
            while (mark < message.length() && message.charAt(mark + 1) == 32) {
                mark++;
            }
            responseCode = Integer.parseInt(message.substring(mark + 1,
                    mark += 4));

⌨️ 快捷键说明

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