Socket - TCP

What is a socket?

Socket is an abstract concept in network programming. We usually use a Socket to represent “a network connection has been opened”, and opening a Socket requires knowing the target computer’s IP address and port number, and then specifying the protocol type.

Introduction to the TCP Protocol

The TCP protocol, Transmission Control Protocol (abbreviated as TCP), is a connection-oriented, reliable, byte-stream-based transport layer communication protocol, defined by IETF’s RFC 793.

TCP communication goes through three steps: creating a connection, data transfer, and terminating the connection. In the TCP communication model, before communication begins, the relevant connection must be created first before data can be sent, similar to “making a phone call” in daily life.

When working, a socket divides the two communicating parties into the server side and the client side, i.e. the C/S model. The TCP communication principle is shown below:

../../../../../../_images/tcp_principle.png

Socket TCP communication process


TCP Programming

This part of the tutorial introduces how to use TCP sockets as a client or a server. For a more comprehensive use of the socket module, please refer to the usocket module. The following tutorial requires a TCP network debugging tool. Below we use iOS’s Network Test Utility, which can be searched and installed on the App Store. For Android, please download: Network Test Utility.apk

Note: here the TCP client (tcpClient) is your computer or phone, and the TCP server (tcpServer) is the mPython Board.

TCP Client

The general steps for the client side of TCP programming are:

  1. Create a socket, using the socket() function

  2. Set socket attributes, using the setsockopt() function, optional

  3. Bind the IP address, port and other information to the socket, using the bind() function, optional

  4. Set the IP address and port and other attributes of the party to connect to

  5. Connect to the server, using the connect() function

  6. Send and receive data, using the send() and recv() functions, or read() and write()

  7. Close the network connection

TCP Client example:
 1import socket
 2from mpython import *
 3
 4host = "172.25.1.63"          # The IP address of the TCP server
 5port = 5001                   # The port of the TCP server
 6s=None
 7
 8mywifi=wifi()                 # Create a wifi class
 9
10
11# Catch exceptions; if the "try" block is interrupted unexpectedly, stop and close the socket
12try:
13    mywifi.connectWiFi("ssid","password")                   # Wi-Fi connection, set ssid and password
14    # mywifi.enable_APWiFi("wifi_name",13)                  # You can also enable AP mode to build your own Wi-Fi network
15    ip=mywifi.sta.ifconfig()[0]                             # Get the local IP address
16    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   # Create a TCP socket, parameters are optional. Defaults to TCP communication
17    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Set the socket attributes
18    s.connect((host,port))                                  # Set the server IP and port to connect to, and connect
19    s.send("hello mPython,I am TCP Client")                 # Send data to the server
20
21    while True:
22        data = s.recv(1024)                                 # Read 1024 bytes of data from the server socket
23        if(len(data) == 0):                                 # If the received data is 0 bytes, close the socket
24            print("close socket")
25            s.close()                                      
26            break
27        print(data)
28        data=data.decode('utf-8')                         # Decode the string with utf-8 encoding
29        oled.fill(0)                                      # Clear the screen
30        oled.DispChar(data,0,0)                           # Display the socket received data on the oled
31        oled.show()                                       # Display
32        s.send(data)                                      # Send the received data to the server
33
34# When an exception is caught, close the socket and network
35except:
36    if (s):
37        s.close()                              
38    mywifi.disconnectWiFi()

Attention

Since data is transmitted in bytes form over the network, attention must be paid to data encoding and decoding.

Attention

In the above example, connectWiFi() is used to connect to the same router’s Wi-Fi. You can also use enable_APWiFi() to enable AP mode and build your own Wi-Fi network for other devices to connect to.

First, the mPython Board and the phone must be connected to the same local area network. Open Network Test Utility, enter the “TCP Server” interface, select the phone’s IP address within that network for the TCP Server IP, and the port number can be set in the range 0~65535. Then click Listen to start listening on the port. Set the TCP server IP address host and port number port selected above in the program, and restart and run the program.

After successfully connecting to the Server, the TCP Server will receive the text hello mPython,I am TCP Client sent by the Client. At this point, when you send text from the TCP Server to the Client, the mPython Board will receive the text and display it on the OLED screen.

../../../../../../_images/socket_1.gif

TCP Server

The general steps for the server side of TCP programming are:

  1. Create a socket, using the socket() function

  2. Set socket attributes, using the setsockopt() function, optional

  3. Bind the IP address, port and other information to the socket, using the bind() function

  4. Start listening and set the maximum number of listeners, using the listen() function

  5. Wait for a client to request a connection, using the accept() function

  6. Send and receive data, using the send() and recv() functions, or read() and write()

  7. Close the network connection

tcpServer example:

TCP Server example:
 1import socket
 2from mpython import *
 3
 4port=5001                   # The port of the TCP server, range 0~65535
 5listenSocket=None              
 6
 7mywifi=wifi()               # Create a wifi class
 8
 9# Catch exceptions; if the "try" block is interrupted unexpectedly, stop and close the socket
10try:
11    mywifi.connectWiFi("ssid","password")                                   # Wi-Fi connection, set ssid and password
12    # mywifi.enable_APWiFi("wifi_name",13)                                  # You can also enable AP mode to build your own Wi-Fi network
13    ip= mywifi.sta.ifconfig()[0]                                            # Get the local IP address
14    listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        # Create a socket, defaults to TCP communication if no parameters given
15    listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)      # Set the socket attribute parameters
16    listenSocket.bind((ip,port))                                            # Bind the ip and port
17    listenSocket.listen(3)                                                  # Start listening and set the maximum number of connections
18    print ('tcp waiting...')
19    oled.DispChar("%s:%s" %(ip,port),0,0)                                   # Display the local server ip and port on the oled screen            
20    oled.DispChar('accepting.....',0,16)                                            
21    oled.show()
22
23    while True:
24        print("accepting.....")
25        conn,addr = listenSocket.accept()                                   # Blocking, wait for the client's connection request; if a new client connects to the server, a new socket is returned dedicated to serving this client
26        print(addr,"connected")                                                         
27    
28        while True:
29            data = conn.recv(1024)                                          # Receive data sent by the other party, read bytes set to 1024
30            if(len(data) == 0):
31                print("close socket")
32                conn.close()                                                # If the received data is 0 bytes, close the socket
33                break
34            data_utf=data.decode()                                          # Decode the received byte stream into a string with utf8 encoding
35            print(data_utf)
36            oled.DispChar(data_utf,0,48)                                    # Display the received text on the oled
37            oled.show()
38            oled.fill_rect(0,48,128,16,0)                                   # Partial screen clear
39            conn.send(data)                                                 # Return data to the client
40
41# When an exception is caught, close the socket and network
42except:
43    if(listenSocket):
44        listenSocket.close()
45    mywifi.disconnectWiFi()

Attention

In the above example, connectWiFi() is used to connect to the same router’s Wi-Fi. You can also use enable_APWiFi() to enable AP mode and build your own Wi-Fi network for other devices to connect to.

First, the mPython Board and the phone must be connected to the same local area network. The mPython Board restarts and runs the program, and the TCP Server side waits for the Client side’s connection request. Open Network Test Utility, enter the “TCP Client” interface, fill in Remote host and port, i.e. the IP address and port of socket.blind(ip,port) . After the Connect connection succeeds, send text; the mPython Board receives the text, displays it on the OLED screen, and returns it to the TCP Client side. You can see the Client->Server, Server->Client process of the text on the phone’s receiving interface.

../../../../../../_images/socket_2.gif