Code example for SocketChannel

Methods: socket, write

0
		ByteBuffer bytebuf = ByteBuffer.wrap(buf);  // wrap the buf into byte buffer
		int nwritten = 0;
		try { 
		    //bytebuf.flip();  // no flip after creating from wrap. 
		    Log.d(TAG, "writeData: start:limit = " + bytebuf.position() + " : " + bytebuf.limit());
		    nwritten = sChannel.write(bytebuf);
		} catch (Exception e) {
		    // Connection may have been closed 
			Log.e(TAG, "writeData: exception : " + e.toString());
			onBrokenConn(sChannel);
		} 
		Log.d(TAG, "writeData: content: " + new String(buf) + "  : len: " + nwritten);
		return nwritten;
	} 
	 
	/** 
	 * server publish data to all the connected clients 
	 */ 
	private void pubDataToAllClients(String msg, SocketChannel incomingChannel){
		Log.d(TAG, "pubDataToAllClients : isServer ? " + mApp.mIsServer + " msg: " + msg );
		if( !mApp.mIsServer ){
			return; 
		} 
		 
		for( SocketChannel s: mClientChannels.values()) {
			if ( s != incomingChannel){
				String peeraddr = s.socket().getInetAddress().getHostAddress();
				Log.d(TAG, "pubDataToAllClients : Server pub data to:  " + peeraddr);
				writeData(s, msg);
			} 
		} 
	} 
	 
	/** 
	 * the device want to push out data. 
	 * If the device is client, the only channel is to the server. 
	 * If the device is server, it just pub the data to all clients for now. 
	 */ 
	public int pushOutData(String jsonString){
		if( !mApp.mIsServer ){   // device is client, can only send to server
			sendDataToServer(jsonString);
		}else{ 
			// server pub to all clients, msg already appended with sender addr inside send button handler. 
			pubDataToAllClients(jsonString, null);
		} 
		return 0; 
	} 
	 
	/** 
	 * whenever client write to server, carry the format of "client_addr : msg " 
	 */ 
	private int sendDataToServer(String jsonString) {
		if(mClientSocketChannel == null) {
			Log.d(TAG, "sendDataToServer: channel not connected ! waiting...");
			return 0; 
		} 
		Log.d(TAG, "sendDataToServer: " + mClientAddr + " -> " + mClientSocketChannel.socket().getInetAddress().getHostAddress() + " : " +  jsonString);
		return writeData(mClientSocketChannel, jsonString);
	} 
}