Python Socket通信例子
Posted 朝花夕拾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Socket通信例子相关的知识,希望对你有一定的参考价值。
一、TCP 通信
- 服务端
#!/usr/bin/env python # -*- coding: utf-8 -*- # server_tcp.py import socket so = socket.socket() so.bind((‘127.0.0.1‘, 8080)) so.listen() while True: conn, addr = so.accept() while True: ret = conn.recv(1024).decode(‘utf-8‘) print(ret) if ret == ‘bye‘: break msg = input("请输入<<< ") if msg == ‘bye‘: conn.send(b‘bye‘) break conn.send(bytes(msg, encoding=‘utf-8‘)) conn.close() so.close()
- 客户端
#!/usr/bin/env python # -*- coding: utf-8 -*- # client_tcp.py import socket so = socket.socket() so.connect((‘127.0.0.1‘, 8080)) while True: msg = input("请输入<<< ") if msg == ‘bye‘: so.send(b‘bye‘) break so.send(bytes(msg, encoding=‘utf-8‘)) ret = so.recv(1024).decode(‘utf-8‘) print(ret) if ret == ‘bye‘: break
二、UDP通信
- 服务端
#!/usr/bin/env python # -*- coding: utf-8 -*- # server_udp.py import socket so = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) so.bind((‘127.0.0.1‘, 8080)) while True: ret, addr = so.recvfrom(1024) print(ret.decode(‘utf-8‘), addr) msg = input("请输入<<< ") so.sendto(bytes(msg, encoding=‘utf-8‘), addr) so.close()
- 客户端
#!/usr/bin/env python # -*- coding: utf-8 -*- # client_udp.py import socket so = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) ip_port = (‘127.0.0.1‘, 8080) while True: msg = input("请输入<<< ") if msg == ‘bye‘: so.sendto(b‘bye‘, ip_port) break so.sendto(bytes(msg, encoding=‘utf-8‘), ip_port) ret, addr = so.recvfrom(1024) print(ret.decode(‘utf-8‘), addr) if ret == ‘bye‘: break so.close()
以上是关于Python Socket通信例子的主要内容,如果未能解决你的问题,请参考以下文章