Python Network Programming - Tcp Client Program Development

TCP client program development Overview

The TCP client needs to establish a connection with the server. After the connection is established successfully, the data transmission can be carried out.
Overview TCP client needs to establish a connection with the server. After the connection is established successfully, data transmission can be performed.
TCP client program development Implementation steps

1. Import the socket package
import socket

2. Create a tcp client socket
socket.AF_INET represents IPv4 type
SOCK_STREAM means tcp
tcp_client_socket = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) _ _ _ _ _ _

3. Establish a connection with the server
connect(host, port) means to establish a connection with the server socket, host is the server ip address, port is the port number of the application
tcp_client_socket.connect (( " 127.0.0.1 " , 9090 ) )

4. Send data to the server
send(data) means to send data, data is binary data
#Data to be sent
send_content = "Hello, I'm Rain"
#Convert to binary data
send_data = send_content.encode ( ' utf - 8' )
#send
tcp_client_socket.send ( send_data ) _ _ _

5. Receive data from the server
recv ( buffersize ) means to receive data, buffersize is the length of each received data
#Receive 1024 bytes each time
recv_data = tcp_client_socket.recv ( 1024 ) _ _ _
#Convert binary data
recv_data_decode = recv_data.decode ( " utf - 8" )
# print received content
print ( "The data received by the client is: " , recv_data_decode )

6. Close the socket
tcp_client_socket.close ( ) _ _

Code
# tcp client program development

import socket

if __name__ == "__main__" :
# 1. Create tcp client socket
# socket.AF_INET represents the IPv4 type
# SOCK_STREAM means tcp
tcp_client_socket = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) _ _ _ _ _ _
# 2. Establish a link with the server
tcp_client_socket.connect ( ( "150.158.5.46 " , 9090 ) )
# 3. Send data to the server
send_content = "Hi, I'm Rain"
send_data = send_content.encode ( ' utf - 8' )
tcp_client_socket.send ( send_data ) _ _ _
# 4. Accept server data
#Receive 1024 bytes each time
recv_data = tcp_client_socket.recv ( 1024 ) _ _ _
#Convert binary data
recv_data_decode = recv_data.decode ( " utf - 8" )
# print received content
# 5. Close the socket
tcp_client_socket.close ( ) _ _

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00