[Python_socket] Socket library in python

Refer to the blog post , thanks.

A simple socket server example:

import socket

s=socket.socket(socket.AFF_INET, socket.SOCK_STRREAM)
s.bind("服务器ip", "服务器端口号")
s.listen(5) #最多允许5个client排队

while True:
    cs, address = s.accept() #cs是新的socket对象,address是接收到的客户端的地址 
    print("got connection from " + str(address))
    cs.send("I have got your socket")
    data = cs.recv(1024) #最多接收1024个字符
    cs.close

A simple socket client example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect("服务器ip", 端口号)

data = s.recv(1024) #从服务器最多接收1024个字符

s.send("this is a connection from client")
print('The data received is '+data)
s.close()

Simply put, both the server and the client need to establish a socket first,

Then, the server uses the .bind method to bind the ip and port, and the client uses the .connect (receive) method to bind the server's ip and port;

Then, the server needs to use .listen(n) to set the maximum number of queues n, and then use the while loop to receive. In the while, first use .accept() to listen to the client, and then use the newly returned sockete port of the .accept() method to send (.send()) and receive (.recv()) messages from the client; the client does not need .listen.accept, but also uses .send and .recv() to send and receive messages.

Guess you like

Origin blog.csdn.net/qq_39642978/article/details/106864354