Introduction

What is TCP

TCPopen in new window (Transmission Control Protocol) The Transmission Control Protocol (TCP) is one of the main protocols of the Internet protocol suite. It originated in the initial network implementation in which it complemented the Internet Protocol (IP). Therefore, the entire suite is commonly referred to as TCP/IP. TCP provides reliable, ordered, and error-checked delivery of a stream of octets (bytes) between applications running on hosts communicating via an IP network. Major internet applications such as the World Wide Web, email, remote administration, and file transfer rely on TCP, which is part of the Transport Layer of the TCP/IP suite. SSL/TLS often runs on top of TCP.

SocketCommunication.kt

In this file to show Kotlin code to connect to host and explain detail of code.

class SocketCommunication(
    private val address: String, //Init address is url or ip
    private val port: Int, // Init port
    private val timeout: Int, // Init timeout connect
) {
    private val socket = Socket() //Initial Socket Library

    // Function Start Socket TCP return type Boolean
    fun run(): Boolean  {
        return try {
            // Socket library initial connection
            socket.connect(InetSocketAddress(address, port), timeout);
            // return true when connected
            socket.isConnected
        } catch(err : Exception) {
            // return false when cannot connect
            socket.isConnected
        }
    }
 
    // Function write Socket TCP return type Boolean
    fun write(message: String): Boolean  {
        return try {
            // Initial write message socket
            val output = DataOutputStream(socket.getOutputStream())
            // Sendout message to destination
            output.write(message.decodeHex())
            // If success return true
            true
        } catch (err: Exception) {
            Log.e("ERR", err.message.toString())
            // If not success return false
            false
        }
    }

    // Initial read message socket
    fun read(): ArrayList<String>  {
        // Set socket timeout
        socket.soTimeout = timeout
        // Initial read message socket
        val input = socket.getInputStream()
        // Calculate max time
        val maxTime = System.currentTimeMillis() + timeout
        // Initial array list
        val isoRespList: ArrayList<String> = ArrayList()
        try {
            // Start while loop with condition is current time is less than max time
            while (System.currentTimeMillis() < maxTime) {
                // Initial input read message
                val content = input.read()

                // Covert byte array to hex string
                val dataList = utils.decimalToHexString(content.toByte())
                // Append data to array list
                isoRespList.add(dataList)
                // Check read message is end?
                if (input.available() == 0) {
                    break;
                }
            }
            // Close connection
            socket.close()
            // Return array list
            return isoRespList
        } catch (err: Exception) {
             // Close connection
            socket.close()
            // Return empty of array list
            return isoRespList
        }
    }

    // Convert hex string to hex byte array
    private fun String.decodeHex(): ByteArray {
        check(length % 2 == 0) { "Must have an even length" }

        return chunked(2)
            .map { it.toInt(16).toByte() }
            .toByteArray()
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

How to use TCP Socket Connection

When whant to make connection use a IP/URL and port to connect to host or application server support this protocol.

Example

URL/IP : 127.0.0.1 PORT: 5000 TIMEOUT: 10000

Initial socket

val socket = 
    SocketCommunication(
        "127.0.0.1",
        5000,
        10000
    )
1
2
3
4
5
6

Check connection

// withContext use when using Jetpack compose UI 
val checkStatus = withContext(Dispatchers.Default) { socket.run() }
1
2

Write message

val writeMessage = socket.write(<message>)
1

Read message

val readStream = withContext(Dispatchers.Default) { socket.read() }
1
Last Updated:
Contributors: Supavit Panyafang