1. Service-side
1.1 Declaring the Socket object
Server=socket.socket (AF. Inet,socket. SOCK_STREAM)
1.2 Binding IP, port
Server.bind (localhost,6969)
1.3 Start monitoring
Server.listen ()
1.4 Receiving the listening connection and address
Conn,addr=server.accept ()
1.5 Receiving data
DATA=CONN.RECV (1024)
Print (data)
1.6 Sending data
Conn.send (data)
1.7. Close the connection
Conn.close ()
import socket#1.实例化socketserver=socket.socket()#2.绑定端口号server.bind((‘localhost‘,6969))#3.开启监听server.listen()print(‘等待连接‘)#4.等待连接conn,addr=server.accept()while True: #5.接收数据 data=conn.recv(1024) if data==‘‘: break print(data.decode()) #6.发送数据 conn.send(‘数据接收成功‘.encode())#7.关闭连接conn.close()
2. Client
2.1 Declaring the Socket object
Client=socket.socket (AF. Inet,socket. SOCK_STREAM)
2.2 Connecting the service side
Client.connect ((' localhost ', 6969))
2.3 Sending data
Client.send (data)
2.4 Receiving data
CLIENT.RECV ()
2.5 Closing the connection
Client.close ()
import socket#1.实例化socketclient=socket.socket()#2.连接服务端client.connect((‘localhost‘,6969))while True: data=input(‘>>:‘) #3.发送数据 client.send(data.encode()) #4.接收数据 data_server=client.recv(1024) print(data_server.decode())client.close()
Python Network programming--socket