在Blackberry上的特定端口上打开http连接

时间:2012-10-22 11:50:40

标签: http blackberry java-me

我知道您可以在Blackberry中编程时打开与URL的连接,但是是否可以在特定端口上打开连接?例如,我想将一些数据发送到服务器的echo端口,以检查它是否处于活动状态并测量ping时间。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情;

// Create ConnectionFactory
ConnectionFactory factory = new ConnectionFactory();

// use the factory to get a connection descriptor
ConnectionDescriptor conDescriptor = factory.getConnection("socket://www.abc.com:portnumber");

您可以在指定打开连接的网址时指定端口号。

答案 1 :(得分:0)

试试这段代码: -

String host  = "Your address" ;

new Thread()
{
    run()
    {
        try {
            SocketConnection connection = (SocketConnection)Connector.open("socket://" + host + ":80");
            OutputStream out = connection.openOutputStream();
            InputStream in = connection.openInputStream();
            // Standard HTTP GET request all in text
            // Only the required Host header, no body
            String request = "GET / HTTP/1.1\r\n" +
                "Host:" + host + "\r\n" +
                "\r\n" +
                "\r\n";
            out.write(request.getBytes());
            out.flush();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int firstByte = in.read();
            if (firstByte >= 0) {
                baos.write((byte)firstByte);
                int bytesAvailable = in.available();
                while(bytesAvailable > 0) {
                    byte[] buffer = new byte[bytesAvailable];
                    in.read(buffer);
                    baos.write(buffer);
                    bytesAvailable = in.available();
                }
            }
            baos.close();
            connection.close();
            final_OP(new String(baos.toByteArray()) );
        } catch (IOException ex) {
            final_OP(ex.getMessage());
        }
    }
}.start();

public void final_OP(final String message) {
    UiApplication.getUiApplication().invokeLater(new Runnable() {
        public void run() {
            Dialog.alert("Output" + message);
        }
    });
}