Code example for SocketChannel

Methods: close, read

1
		if (this.readyState != ReadyState.CLOSED) {
			if (this.socketChannel instanceof SocketChannel) {
				this.readyState = ReadyState.CLOSING;
				try { 
					// Close the SocketChannel, which should kill the thread 
					this.socketChannel.close();
				} catch (IOException ex) {
				} 
			} 
		} 
	} 
 
	/** 
	 * Send a message through the WebSocket 
	 *  
	 * @param data 
	 *            Data to send 
	 */ 
	public void send(String data) throws IllegalArgumentException,
			NotYetConnectedException { 
		if (this.readyState == ReadyState.OPEN) {
			if (data == null || data.equals("")) {
				throw new IllegalArgumentException(
						"WebSocket cannot send an empty string"); 
			} 
			try { 
				// Create the socket message with framing bytes 
				byte[] messageBuffer = data.getBytes(WebSocket.ENCODING);
				ByteBuffer buffer = ByteBuffer
						.allocate(messageBuffer.length + 2);
				buffer.put(WebSocket.START_TEXT_FRAME);
				buffer.put(messageBuffer);
				buffer.put(WebSocket.END_FRAME);
				// Write the buffer the socket 
				buffer.rewind();
				this.socketChannel.write(buffer);
			} catch (IOException ex) {
			} 
		} else { 
			throw new NotYetConnectedException();
		} 
	} 
 
	/** 
	 * Runnable interface implementation. Initializes socket connection 
	 */ 
	public void run() { 
		if (this.readyState == ReadyState.CLOSED) {
			this.hasConnected = false;
			try { 
				// Flag the connection as connecting 
				this.readyState = ReadyState.CONNECTING;
 
				// Get the socket port 
				int port = this.uri.getPort();
				if (port == -1) {
					port = 80;
				} 
 
				// Android 2.2 prefers IPv6, but throws 
				// "java.net.SocketException: Address family not supported by protocol" 
				System.setProperty("java.net.preferIPv6Addresses", "false");
				// Create a non-blocking SocketChannel 
				SocketAddress socketAddress = new InetSocketAddress(uri
						.getHost(), port);
				this.socketChannel = SocketChannel.open();
				this.socketChannel.configureBlocking(false);
				this.socketChannel.connect(socketAddress);
 
				// Create a Selector and attach to SocketChannel 
				Selector selector = Selector.open();
				this.socketChannel.register(selector, this.socketChannel
						.validOps());
 
				// Loop until SocketChannel closes (500 ms timeout) 
				while (selector.select(500) > 0 && selector.isOpen()) {
					// Iterate over the selection keys with pending events 
					Set<SelectionKey> keys = selector.selectedKeys();
					Iterator<SelectionKey> iterator = keys.iterator();
					while (iterator.hasNext()) {
						// Get the selection key and remove it from the set 
						SelectionKey key = iterator.next();
						iterator.remove();
 
						// Check if connection is established 
						if (key.isValid() && key.isConnectable()) {
							this.handleConnect(key);
						} 
 
						// Check if the connection can read 
						if (key.isValid() && key.isReadable()) {
							this.handleRead();
						} 
					} 
				} 
			} catch (UnsupportedEncodingException ex) {
			} catch (IOException ex) {
			} 
			// Set the ready state to closed 
			this.readyState = ReadyState.CLOSED;
			Boolean notifyClosed = this.hasConnected;
			this.hasConnected = false;
			// Check if need to notify of close 
			if (notifyClosed) {
				System.out.println("*** WebSocket CLOSED ***");
				// Check if a listener is defined and notify 
				if (this.listener != null
						&& this.listener instanceof WebSocketListener) {
					this.listener.onClose(this);
				} 
			} 
		} 
	} 
 
	// -------------------------------------------------- 
	// Private Methods 
	// -------------------------------------------------- 
 
	/** 
	 * Initialize the WebSocket with URI and sub-protocol 
	 *  
	 * @param uri 
	 *            URI to connect to 
	 * @param protocol 
	 *            Sub-protocol that the server must support 
	 */ 
	private void initialize(URI uri, String protocol) {
		// Set the unique ID 
		this.id = UUID.randomUUID().toString();
 
		// Check if the scheme is valid and store URI and protocol 
		String scheme = uri.getScheme();
		if (scheme.equals("ws") || scheme.equals("wss")) {
			this.uri = uri;
			this.subProtocol = protocol;
		} else { 
			throw new IllegalArgumentException("Invalid scheme: " + uri);
		} 
		// Initialize headers collection and buffers 
		this.headers = new HashMap<String, String>();
		this.readBuffer = ByteBuffer.allocate(1);
		this.frameBuffer = null;
	} 
 
	/** 
	 * Handle connection to host 
	 *  
	 * @param key 
	 *            SelectionKey instance to connect 
	 * @throws IOException 
	 */ 
	private void handleConnect(SelectionKey key) throws IOException,
			UnsupportedEncodingException { 
		// Ensure connection is finished 
		if (this.socketChannel.isConnectionPending()) {
			this.socketChannel.finishConnect();
		} 
		// Send WebSocket client handshake 
		this.socketChannel.write(ByteBuffer.wrap(this.createHandshake()));
	} 
 
	/** 
	 * Handle reading from SocketChannel 
	 *  
	 * @throws IOException 
	 */ 
	private void handleRead() throws IOException { 
		// Read from the SocketChannel 
		this.readBuffer.rewind();
		int bytesRead = -1;
		try { 
			bytesRead = this.socketChannel.read(this.readBuffer);
		} catch (Exception ex) {
			@SuppressWarnings("unused") 
			String test = ex.getMessage();
		} 
		if (bytesRead == -1) {