sk = socket.socket() sk.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # 此处作用解决Address already in use的情况,可以加入socket配置重用ip和端口 sk.bind(('127.0.0.1', 8088)) sk.listen() conn, addr = sk.accept() whileTrue: res = conn.recv(1024).decode('utf-8') if res == 'bye': break else: print(res) info = input('请输入:\n>>>').encode('utf-8') conn.send(info) conn.close() sk.close()
# ---------- 客户端 ---------- import socket
sk= socket.socket() sk.connect(('127.0.0.1', 8088)) whileTrue: info = input('请输入:\n>>>').encode('utf-8') sk.send(info) res = sk.recv(1024).decode('utf-8') if res == 'bye': break else: print(res) sk.close()
sk = socket.socket() sk.bind(('127.0.0.1', 8088)) # listen([backlog])中的[backlog]参数代表服务端允许多少客户端连接到服务端,即阻塞队列长度,所以一共能与服务器连接的客户端共有backlog+1个 sk.listen(3) whileTrue: conn, addr = sk.accept() # sk.accept()放在循环内部是为了每次与同一个客户端交互结束后会重新建立conn连接,以便下一个客户端连入 res = conn.recv(1024).decode('utf-8') if res == 'bye': break else: print('收到',res) info = input('请输入>>>').encode('utf-8') conn.send(info) conn.close() # 同上面sk.accept()的作用 sk.close()
# ---------- 客户端 ---------- import socket
sk = socket.socket() sk.connect(('127.0.0.1', 8088)) whileTrue: info = input('请输入>>>').encode('utf-8') if info == 'bye': break else: sk.send(info) res = sk.recv(1024).decode('utf-8') print(res) sk.close()