Android Open Source - MessengerApp Tcp Receiver Worker

From Project

Back to project page MessengerApp.


The source code is released under:

MIT License

If you think the Android project MessengerApp listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.example.myfirstapp;
//from   ww w  .ja v  a 2  s.c om
import java.util.Queue;

import android.os.Handler;

 * TCP Receiver Worker to handle established incoming connections.
 * @author Shung-Hsi Yu <> ID#0906172
 * @version Apr 11, 2014
public class TcpReceiverWorker implements Runnable {
    private Socket sender;
    private final Queue<String> uiMessageQueue;
    private Handler mHandler;

     * Constructor for TcpReceiverWorker class.
     * @param sender the socket object that is connect to the sender
     * @param uiMessageQueue Queue which will take the received messages
    public TcpReceiverWorker(Socket sender, Queue<String> uiMessageQueue, Handler mHandler) {
        this.mHandler = mHandler;
      this.sender = sender;
        this.uiMessageQueue = uiMessageQueue;
     * Default method called by thread objects.
    public void run() {
        try {
          BufferedReader in = new BufferedReader(
              new InputStreamReader(
            String message = getWholeMessage(in);
            showMessage(sender.getInetAddress(), message);
        } catch (IOException e) {
            // TODO write error recovery code
            System.out.println(":: Can't retrieve message");
     * Retrieve the whole message, rather than retrieving a line.
     * @param in BufferedReader instance to read from
     * @return the message in the specified BufferedReader instance
     * @throws IOException 
    private String getWholeMessage(BufferedReader in) throws IOException {
        StringBuilder sb = new StringBuilder();
        String input = in.readLine();
        while (input != null) {
            input = in.readLine();
        return sb.toString();
     * Display the retrieved message according to the implementation. This
     * implementation simple add the message to a queue.
     * @param senderIp IP adress of the sender
     * @param message the message to display
    private void showMessage(InetAddress senderIp, String message) {
        uiMessageQueue.add(senderIp.getHostAddress() + ": " + message);


Java Source Code List