网络编程-socket实现连接循环
解决报端口被使用错误
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR)
bug 1:客户端敲回车被卡主,客户端被卡在recv等待接收数据
import socket client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(('127.0.0.1',8080)) #通信循环 while True: msg=input('>> ').strip() if not msg:continue#避免用户输入空字符串导致客户端卡死 client.send(msg.encode('utf-8')) data=client.recv(1024).decode('utf-8') print(data) #关闭连接 client.close()
bug 2:客户端单方面断开后,linux平台上服务端会出现死循环接收数据,导致服务器卡死。window平台会直接报错。
Linux服务端
import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #解决提示端口被使用问题 phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(('127.0.0.1',8080)) phone.listen(5) conn,client_addr=phone.accept() print(client_addr) #通信循环 while True: data=conn.recv(1024) if not data:break#客户端单方面死掉,服务端会收到空字符串 conn.send(data.upper()) conn.close() phone.close()
Windows服务端
import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #解决提示端口被使用问题 phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(('127.0.0.1',8080)) phone.listen(5) conn,client_addr=phone.accept() print(client_addr) #通信循环 while True: try: data=conn.recv(1024) conn.send(data.upper()) except ConnectionResetError: break conn.close() phone.close()
客户端
import socket client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(('127.0.0.1',8080)) #通信循环 while True: msg=input('>> ').strip() if not msg:continue#避免用户输入空字符串导致客户端卡死 client.send(msg.encode('utf-8')) data=client.recv(1024).decode('utf-8') print(data) #关闭连接 client.close()
实现server端循环连接:
import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #解决提示端口被使用问题 phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(('127.0.0.1',8080)) phone.listen(5) while True:#连接循环 conn,client_addr=phone.accept() print(client_addr) while True:#通信循环 try: data=conn.recv(1024) if not data: break # 客户端单方面死掉,服务端会收到空字符串 conn.send(data.upper()) except ConnectionResetError: break conn.close()#连接关闭 phone.close()#套接字关闭