Code example for Socket

Methods: close, isConnected

0
            return false; 
        } 
 
        try { 
            // send the message 
            this.sock = new Socket(hostname, port);
            this.io = new ByteArrayIOChannel(sock);
 
            io.send(message.getBytes());
 
            // get a response 
            byte[] b = io.recv();
 
            if (b == null || b.length == 0) {
                if (debug) {
                    System.err
                            .println("empty response from adapter during connect.");
                } 
                return false; 
            } 
 
            String response = new String(b);
 
            JSONObject json = new JSONObject(response);
            String s = json.optString("status", "unknown");
 
            // does it look OK? 
            if (s.equalsIgnoreCase("ok")) {
                // done connecting 
                state = State.Connected;
                return true; 
            } else if (s.equalsIgnoreCase("failed")) {
                // server has failed the connect attempt 
                if (debug) {
                    System.err.println("connect failed by adapter. reason: "
                            + json.optString("reason", "unknown"));
                } 
                return false; 
            } else { 
                // unknown response. 
                if (debug) {
                    System.err
                            .println("connect failed by adapter. unrecongnized response: "
                                    + response);
                } 
                return false; 
            } 
 
        } catch (Exception e) {
            // clean up after error... 
            if (debug) {
                System.err.println("error during connect: " + e);
                e.printStackTrace();
            } 
 
            if (this.sock.isConnected()) {
                this.sock.close();
 
            } 
 
            return false; 
        }