Code example for Socket

Methods: bind, connect, getOutputStream, isConnected

0
	protected void onHandleIntent(Intent intent) {
 
		if (intent.getAction().equals(ACTION_SEND_MESSAGE)) {
			String messageString = intent.getExtras().getString(EXTRAS_MESSSGE_STRING);
			String host = intent.getExtras().getString(EXTRAS_ADDRESS);
			Socket socket = new Socket();
			int port = intent.getExtras().getInt(EXTRAS_PORT);
 
			try { 
				Log.d("MessageTransferService", "Opening client socket - host: " + host);
				socket.bind(null);
				socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
				Log.d("MessageTransferService", "Client socket - " + socket.isConnected());
				OutputStream os = socket.getOutputStream();
 				byte[] stringByte = messageString.getBytes();
 				os.write(stringByte);
 				os.close();
				Log.d("MessageTransferService", "Client: Data written");
			} catch (IOException e) {
				Log.e("MessageTransferService", e.getMessage());
			} finally { 
				if (socket != null) {
					if (socket.isConnected()) {
						try { 
							socket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}