Use python to realize TCP protocol transmission function (client code)

The key of TCP transmission is to have a socket (socket), so the socket module is used in the code.
The environment needed to realize the principle is a windows computer , a linux virtual machine , and the relevant python code is written under the linux virtual machine. Install the network debugging assistant under windows
Insert picture description here
At this time, choose your own windows computer as the server, and the linux virtual machine as the client. The
py code is as follows:

import socket


if __name__ == '__main__':
	# 首先创建好客户端的套接字socket,这个是socket模块下的一个类,其中第一个参数是ipv4协议的意思,第二个参数是选择了TCP协议
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 此段代码代表这个客户端与服务端进行连接,其中8080是服务端开启的端口(我所用的服务端为windows电脑)
    tcp_client_socket.connect(("192.168.99.1", 8080))
    # 下面写好准备发送的数据,因为TCP协议是以字节流的形式发送,所以要用encode方法去编译代码
    send_data = "hello python".encode("utf-8")
    # 发送数据
    tcp_client_socket.send(send_data)
    # 养成良好习惯,发完数据后关闭套接字
    tcp_client_socket.close()

After running the code, we can see under the network debugging assistant under the windows computer: it
Insert picture description here
means that we have sent successfully, and the server has received the request from the client

Guess you like

Origin blog.csdn.net/weixin_48445640/article/details/108890976