Python的socket通信
程序员文章站
2022-07-07 15:26:11
...
python中的socket模块封装了底层的TCP/IP等协议的实现细节,将其隐藏在socket接口中。
TCP使用三次握手建立连接,四次握手断开连接。原理:连接时可靠,并且发送消息有确认回复机制,保证消息可靠传输。四次握手因为客户端断开连接后服务器可能还有数据要传送,所以不能与确认命令一起发送,故比建立连接多一次握手。
简单实现C/Ssocket通信例子
TCP:server端:
# import socket
from socket import *
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024
tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)
while True:
print('服务端开始运行了')
conn,addr=tcp_server.accept() #服务端阻塞
print('双向链接是',conn)
print('客户端地址',addr)
while True:
# try:
data=conn.recv(buffer_size)
print('客户端发来的消息是',data.decode('utf-8'))
conn.send(data.upper())
# except Exception:
# break
conn.close()
tcp_server.close()
TCP:客户端
# import socket
from socket import *
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024
tcp_client=socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)
while True:
msg=input('>>: ').strip()
if not msg:continue
tcp_client.send(msg.encode('utf-8'))
print('客户端已经发送消息')
data=tcp_client.recv(buffer_size)
print('收到服务端发来的消息',data.decode('utf-8'))
tcp_client.close()
UDP:server端
from socket import *
ip_port=('127.0.0.1',8080)
buffer_size=1024
udp_server=socket(AF_INET,SOCK_DGRAM) #数据报
udp_server.bind(ip_port)
while True:
data,addr=udp_server.recvfrom(buffer_size)
print(data)
udp_server.sendto(data.upper(),addr)
UDP:客户端
from socket import *
ip_port=('127.0.0.1',8080)
buffer_size=1024
udp_client=socket(AF_INET,SOCK_DGRAM) #数据报
while True:
msg=input('>>: ').strip()
udp_client.sendto(msg.encode('utf-8'),ip_port)
data,addr=udp_client.recvfrom(buffer_size)
# print(data.decode('utf-8'))
print(data)
利用socketserver实现TCP多线程通信
# 服务端
import socketserver
'''
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
self.setup()
try:
self.handle()
finally:
self.finish()
'''
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
print('conn is: ',self.request) #conn
print('addr is: ',self.client_address) #addr
while True:
try:
#收消息
data=self.request.recv(1024)
if not data:break
print('收到客户端的消息是',data,self.client_address)
#发消息
self.request.sendall(data.upper())
except Exception as e:
print(e)
break
if __name__ == '__main__':
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) #多线程
# s=socketserver.ForkingTCPServer(('127.0.0.1',8080),MyServer) #多进程
# self.server_address = server_address
# self.RequestHandlerClass = RequestHandlerClass
print(s.server_address)
print(s.RequestHandlerClass)
print(MyServer)
print(s.socket)
print(s.server_address)
s.serve_forever()
# 客户端 拷贝多份执行可同时与服务端通信
from socket import *
import struct
from functools import partial
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024
tcp_client=socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)
while True:
cmd=input('>>: ').strip()
if not cmd:continue
if cmd == 'quit':break
tcp_client.send(cmd.encode('utf-8'))
recv_data = tcp_client.recv(buffer_size)
recv_size=len(recv_data)
print('命令的执行结果是 ',recv_data.decode('gbk'))
tcp_client.close()