Mohammad Farahi
Mohammad Farahi

Reputation: 1066

Android - Convert TCP Client to UDP Client

I have a working code of running TCP connection with send and receive. Here is my CreateCommThreadTask , WriteToServer and CloseSocketTask Classes:

    private class CreateCommThreadTask extends AsyncTask
        <Void, Integer, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            //---create a socket---
            serverAddress =
                    InetAddress.getByName("192.168.4.1");
            socket = new Socket(serverAddress, 8080);
            commsThread = new CommsThread(socket);
            commsThread.start();
        } 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;
    }
}

And With this Class I read incoming data:

public 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 {
        //---creates the inputstream and outputstream objects
        // for reading and writing through the sockets---
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.d("SocketChat", e.getLocalizedMessage());
    } 
    inputStream = tmpIn;
    outputStream = tmpOut;
}

public void run() {
    //---buffer store for the stream---
    byte[] buffer = new byte[1024];

    //---bytes returned from read()---
    int bytes;  

    //---keep listening to the InputStream until an 
    // exception occurs---
    while (true) {
        try {
            //---read from the inputStream---
            bytes = inputStream.read(buffer);

            //---update the main activity UI---
            SocketsActivity.UIupdater.obtainMessage(
                0,bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

//---call this from the main activity to 
// send data to the remote device---
public void write(byte[] bytes) {
    try {
        outputStream.write(bytes);
    } catch (IOException e) { }
}

//---call this from the main activity to 
// shutdown the connection--- 
public void cancel() {
    try {
        socket.close();
    } catch (IOException e) { }
}

}

finally I use my received data using a Handler Like This:

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


        //---convert the entire byte array to string---
        //---extract only the actual string received---
        if(numOfBytesReceived>0)
        {
            strReceived = new String(buffer);
            strReceived = strReceived.substring(0, numOfBytesReceived);
        }
        //---display the text received on the TextVie*---

    }
};

These code works fine in TCP connection. My question is what changes is needed to convert these to UDP Client? I want to implement UDP in AsyncTask same as TCP code I wrote.

Upvotes: 1

Views: 1432

Answers (3)

from56
from56

Reputation: 4127

A main difference between TCP & UDP is that TCP is a connected socket, you first need to establish a connection and then send or receive packets. Instead with UDP you directly send a packet to an IP + Destination Port with out previous connection, it is an unconnected socket.

With UDP the packet size is limited, recommended not to exceed 512 bytes, instead with TCP there's not limit.

With UDP there is no guarantee that the packet will be received on the other side, and the sender will not have any confirmation of whether it was received, instead on TCP there is such a verification.

if you need a connection that ensures that the bytes sent are received on the other side, you need to use TCP and not UDP

And also be aware that actually some mobile phone companies don't assign any more public IP to clients, they assign private IP. In this situation the Android device can't act as server, that means can't wait for received UDP packets and can't listen for incoming TCP connections due its ports are inaccessible from the WAN.

Upvotes: 0

Nabin Bhandari
Nabin Bhandari

Reputation: 16399

To use UDP, you should use DatagramSocket

To send a message:

DatagramSocket serverSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(ipAddress);
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);

To receive a message:

byte[] receiveData = new byte[15]; //max length 15.
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
DatagramSocket clientSocket = new DatagramSocket(port);
clientSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData()).trim();

Upvotes: 1

mrg
mrg

Reputation: 332

You should use DatagramSocket and DatagramPacket. Here is a nice tutorial - Writing a Datagram Client and Server.

Upvotes: 0

Related Questions