socket模块相关的方法和类
socket.socket()
:返回一个 socket对象。socket.create_connection(address)
:创建一个连接到给定地址的 socket对象(注意:此处的 address是一个二元元组(host, port)。注意:上面两点中的 socket指 socket模块,以下的 socket均指 socket对象。
socket.bind(address)
:将 socket对象绑定到给定的地址上。socket.listen()
:监听 socket绑定的地址,在调用该方法后如果有连接请求,就可以调用socket.accept()
接受连接。socket.accept()
:在调用socket.listen()
方法后,调用该方法来接受连接请求。socket.connect(address)
:连接到给定地址。socket.send(bytes)
:发送二进制数据。socket.recv(bufsize)
:接受一段 bufsize大小的数据,通常 bufsize是 2的 n次方,如 1024,40258等。
简单的 socket服务器端
import socket HOST = '127.0.0.1'PORT = 8888server = socket.socket() server.bind((HOST, PORT)) server.listen(1) print(f'the server is listening at {HOST}:{PORT}') print('waiting for conntection...') conn, addr = server.accept() print(f'connect success addr={addr}') print('waiting for message')while True: msg = conn.recv(1024) print('the clint send:', msg.decode()) response = input('enter your response: ') conn.send(response.encode()) print('waiting for answer')
简单的 socket客户端
import socketimport systry: host, port = input('please enter host address like host:port: ').split(':')except ValueError: print('the address is wrong') sys.exit(-1)if len(host) == 0 or len(port) == 0: print('the address is wrong') sys.exit(-1)else: client = socket.create_connection((host, int(port))) print('connect successfully. waiting for response...') client.send(b'hello server.') while True: response = client.recv(1024) print('the response is:', response.decode()) msg = input('please enter a answer: ') client.send(msg.encode()) print('waiting for response...')
运行截图:
作者:渔父歌
链接:https://www.jianshu.com/p/b8c154081ca9