Python编程之socket
Posted 高母寨寨委书记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python编程之socket相关的知识,希望对你有一定的参考价值。
1、TCP
客户端:
from socket import * ip_port = ("127.0.0.1",8888) back_log = 5 buffer_size = 1024 tcp_client = socket(AF_INET,SOCK_STREAM) tcp_client.connect(ip_port) while 1: msg = input(">>>>>>>:").strip() if not msg:continue tcp_client.send(msg.encode("utf-8")) print("客户端已发送消息",msg) data = tcp_client.recv(buffer_size) print("客户端收到的数据是",data.decode("utf-8")) tcp_client.close()
服务端:
from socket import * ip_port = ("127.0.0.1",8888) back_log = 5 buffer_size = 1024 tcp_server = socket(AF_INET,SOCK_STREAM) tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)#解决服务端断开延时问题 tcp_server.bind(ip_port) tcp_server.listen(back_log) print("服务端开始运行了") while 1: conn,adr = tcp_server.accept()#服务端阻塞 print("双向连接是",conn) print("客户端地址是",adr) while 1: try: data = conn.recv(buffer_size) print("客户端发来的消息是",data.decode("utf-8")) conn.send(data.upper()) print("服务端回复的消息是",data.upper(),"客户端消息回复成功") except Exception: break conn.close() tcp_server.close()
以上是关于Python编程之socket的主要内容,如果未能解决你的问题,请参考以下文章