socket是一个模块, 又称套接字,用来封装 互联网协议(应用层以下的层)。
socket可以实现互联网协议 应用层以下的层 的工作,提高开发效率。
‘‘‘ client.py启动服务端后再启动客户端 ‘‘‘ import socket #1.买手机 client = socket.socket() #拿到一个手机对象 #2.拨号 client.connect((‘127.0.0.1‘,9527)) #客户端的ip和port必须与服务器一致 print(‘client is running‘) #3.通信循环 #讲话给对方听 while True: send_data = input(‘客户端>>>:‘) client.send(send_data.encode(‘utf-8‘)) #只能发bytes类型 data = client.recv(1024) if data.decode(‘utf-8‘) == ‘q‘: break if len(data) == 0: break print(data.decode(‘utf-8‘)) #4.断开连接 client.close()
‘‘‘ server.py先启动套接字服务端 注意: 客户端发送一次消息,服务端就得接受一次,再发送消息。 ‘‘‘ import socket #1.买手机 server = socket.socket() #拿到一个手机对象 # print(server) # server是用来收发链接请求,建立链接 #2.绑手机卡 server.bind((‘127.0.0.1‘,9527)) #0-65535 #本地回环地址 ---》‘127.0.0.1‘ #3.开机(半连接池) server.listen(5) #同一时刻,最大请求数为5个 实际==6 print(‘sever is running‘) #4.等待电话请求 #conn:指的是服务端往客户端的管道 #conn,addr = server.accept() #(双向连接的套接字对象,存放客户端IP和端口的小元组) # print(conn) #conn代表双向链接,用来收发链接 #5.循环实现可接受多个用户访问 while True: #等待电话接入 --->接入客户端 # conn: 指的是服务端往客户端的管道 conn,addr = server.accpt() print(addr) #实现循环通信 while True: try: #监听代码块是否有异常出现 # 接受对方讲话的内容 # data --->客户端发送过来的消息 data = conn.recv(1024) #1024接受的最大字节数bytes if len(data) == 0: break if data.decode(‘utf-8‘) == ‘q‘: break print(data.decode(‘utf-8‘)) send_data = input(‘服务器>>>:‘) #服务器往客户端发送消息 conn.send(send_data.encode(‘utf-8‘)) # 捕获异常信息,并打印 # e: 报错信息 except Exception as e: print(e) break #6.挂电话连接 conn.close()
import socket #client client = socket.socket() client.connect((‘127.0.0.1‘,9500)) print(‘Client is running‘) while True: msg = input(‘客户端:‘).encode(‘utf-8‘) client.send(msg) data = client.recv(1024) print(data)
import socket from threading import Thread #server #封装成函数 def communicate(conn): while True: #通信循环 try: data = conn.recv(1024) if len(data) == 0: break print(data.decode(‘utf-8‘)) conn.send(‘好啊‘.encode(‘utf-8‘)) except Exception as e: print(e) break conn.close() def server(backlog=5): server = socket.socket() server.bind((‘127.0.0.1‘,9500)) server.listen(backlog) while True: #链接循环 conn,addr = server.accept() print(addr) t = Thread(target=communicate,args=(conn,)) t.start() if __name__ == ‘__main__‘: t = Thread(target=server) t.start()
版本二:半连接池版
import socket #client client = socket.socket() client.connect((‘127.0.0.1‘,9500)) print(‘Client is running‘) while True: msg = input(‘客户端:‘).encode(‘utf-8‘) client.send(msg) data = client.recv(1024) print(data)
import socket from concurrent.futures import ThreadPoolExecutor server = socket.socket() server.bind((‘127.0.0.1‘,9500)) server.listen(5) #封装成一个函数 def run(conn): while True: try: data = conn.recv(1024) if len(data) == 0: break print(data.decode(‘utf-8‘)) conn.send(‘好啊‘.encode(‘utf-8‘)) except Exception as e: print(e) break conn.close() if __name__ == ‘__main__‘: print(‘Server is running‘) pool = ThreadPoolExecutor(100) while True: conn,addr = server.accept() pool.submit(run,conn)
原文:https://www.cnblogs.com/wddxx/p/13672260.html