CodeByte

Write your code smartly

Simple TCP Client Server Communication using Android

The following post is about simple TCP Client Server communication sample using Java code for Android. The steps are simple as defined below. TCP communication is done over inter-network or internal network (not necessary internet working). There must be an IP-Address for destination and a unique port (with unique I mean is not one which is used for standard protocols such as File Transfer Protocol (FTP) uses port number 21, TCP uses port 80) list can be found here for more reference. The port range is from 1 to 65535. Selecting a port from this range and an IP address, you can simply transmit data over network directly to the destination port.

TCP Client connection to TCP server to send data


try{
// Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
Socket s = new Socket("192.168.1.1", 5555);

// Initialize output stream to write message to the socket stream
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

String outMsg = "";

outMsg = "This is Client";

// Write message to stream
out.write(outMsg);

// Flush the data from the stream to indicate end of message
out.flush();

// Close the output stream
out.close();

// Close the socket connection
s.close();
}

catch(Exception ex){
//:TODO Handle exceptions
}

A simple TCP server to receive the TCP packet from client.

TCP Server receive the data using the port as IP address is just mentioned from the source and not required anywhere for TCP Server.


try{

ServerSocket ss = null;

// Initialize Server Socket to listen to its opened port
ss = new ServerSocket(5555);

// Accept any client connection
Socket s = ss.accept();

// Initialize Buffered reader to read the message from the client
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

// Get incoming message
String incomingMessage = in.readLine() + System.getProperty("line.separator");

// Use incomingMessage as required
System.out.print(incomingMessage);

// Close input stream
in.close();

// Close Socket
s.close();

// Close server socket
ss.close();

}
catch(Exception ex){
//:TODO Handle exceptions
}

You can utilize the received message accordingly.

To test the working example on Android devices you must add permissions to AndroidManifest.xml

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

Cheers !

 

Leave a comment