Android How to - Talk to a Socket Server








The following code shows how to Talk to a Socket Server.

Example

Add the following line to the AndroidManifest.xml file:


<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        ...
    </application>

</manifest>

Main layout xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<EditText
    android:id="@+id/txtMessage"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Message"
    android:onClick="onClickSend"/>

<TextView
    android:id="@+id/txtMessagesReceived"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:scrollbars = "vertical" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication4.app;
//from  www.ja v a2 s.c o m
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.util.Log;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    InetAddress serverAddress;
    Socket socket;

    static TextView txtMessagesReceived;
    EditText txtMessage;

    CommsThread commsThread;

    static Handler UIupdater = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int numOfBytesReceived = msg.arg1;
            byte [] buffer = (byte []) msg.obj;

            String strReceived = new String(buffer);

            strReceived = strReceived.substring(
                    0, numOfBytesReceived);

            txtMessagesReceived.setText(
                    txtMessagesReceived.getText().toString() +
                            strReceived);
        }
    };

    private class CreateCommThreadTask extends AsyncTask
            <Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                serverAddress =
                        InetAddress.getByName("192.168.1.101");
                socket = new Socket(serverAddress, 500);
                commsThread = new CommsThread(socket);
                commsThread.start();
                sendToServer("hi");
            } catch (UnknownHostException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

    private class WriteToServerTask extends AsyncTask
            <byte [], Void, Void> {
        protected Void doInBackground(byte []...data) {
            commsThread.write(data[0]);
            return null;
        }
    }

    private class CloseSocketTask extends AsyncTask
            <Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                socket.close();
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtMessage = (EditText) findViewById(R.id.txtMessage);
        txtMessagesReceived = (TextView)
                findViewById(R.id.txtMessagesReceived);
    }

    public void onClickSend(View view) {
        sendToServer(txtMessage.getText().toString());
    }

    private void sendToServer(String message) {
        byte [] theByteArray =
                message.getBytes();
        new WriteToServerTask().execute(theByteArray);
    }

    @Override
    public void onResume() {
        super.onResume();
        new CreateCommThreadTask().execute();
    }

    @Override
    public void onPause() {
        super.onPause();
        new CloseSocketTask().execute();
    }
}
class CommsThread extends Thread {
    private final Socket socket;
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public CommsThread(Socket sock) {
        socket = sock;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.d("SocketChat", e.getLocalizedMessage());
        }
        inputStream = tmpIn;
        outputStream = tmpOut;
    }

    public void run() {
        byte [] buffer = new byte [1024];

        int bytes;

        while (true) {
            try {
                bytes = inputStream.read(buffer);

                MainActivity.UIupdater.obtainMessage(
                        0,bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte [] bytes) {
        try {
            outputStream.write(bytes);
        } catch (IOException e) { }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) { }
    }
}