Python Socket学习
Python 在网络通讯方面功能强大,学习一下 Socket 通讯的基本方式
UDP 通讯:
Server:
import socket port=8081 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #从指定的端口,从任何发送者,接收 UDP 数据 s.bind(('',port)) print('正在等待接入...') while True: #接收一个数据 data,addr=s.recvfrom(1024) print('Received:',data,'from',addr)
Client:
import socket port=8081 host='localhost' s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.sendto(b'hello,this is a test info !',(host,port))
很简单 。下面是 TCP 方式:
Server:
#-*- coding: utf-8 -*- from socket import * from time import ctimeHOST=''
PORT=12345
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)sock.bind(ADDR)
sock.listen(5)
while True:
print('waiting for connection')
tcpClientSock, addr=sock.accept()
print('connect from ', addr)
while True:
try:
data=tcpClientSock.recv(BUFSIZ)
except:
print(e)
tcpClientSock.close()
break
if not data:
break
s='Hi,you send me :[%s] %s' %(ctime(), data.decode('utf8'))
tcpClientSock.send(s.encode('utf8'))
print([ctime()], ':', data.decode('utf8'))
tcpClientSock.close()
sock.close()
Client:
#-*- coding: utf-8 -*- from socket import *class TcpClient:
HOST='127.0.0.1'
PORT=12345
BUFSIZ=1024
ADDR=(HOST, PORT)
def init(self):
self.client=socket(AF_INET, SOCK_STREAM)
self.client.connect(self.ADDR)</span><span style="color: rgba(0, 0, 255, 1)">while</span><span style="color: rgba(0, 0, 0, 1)"> True: data</span>=input(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">></span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> data: </span><span style="color: rgba(0, 0, 255, 1)">break</span><span style="color: rgba(0, 0, 0, 1)"> self.client.send(data.encode(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)) data</span>=<span style="color: rgba(0, 0, 0, 1)">self.client.recv(self.BUFSIZ) </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> data: </span><span style="color: rgba(0, 0, 255, 1)">break</span> <span style="color: rgba(0, 0, 255, 1)">print</span>(data.decode(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">))
if name == 'main':
client=TcpClient()
上面的 TCP 方式有个问题,不能退出,好吧,我们改造一下,使这个程序可以发送 quit 命令以退出:
Server:
#-*- coding: utf-8 -*- from socket import * from time import ctime from time import localtime import timeHOST=''
PORT=1122 #设置侦听端口
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)sock.bind(ADDR)
sock.listen(5)
#设置退出条件
STOP_CHAT=False
while not STOP_CHAT:
print('等待接入,侦听端口:%d' % (PORT))
tcpClientSock, addr=sock.accept()
print('接受连接,客户端地址:',addr)
while True:
try:
data=tcpClientSock.recv(BUFSIZ)
except:
#print(e)
tcpClientSock.close()
break
if not data:
break
#python3 使用 bytes,所以要进行编码
#s='%s 发送给我的信息是:[%s] %s' %(addr[0],ctime(), data.decode('utf8'))
#对日期进行一下格式化
ISOTIMEFORMAT='%Y-%m-%d %X'
stime=time.strftime(ISOTIMEFORMAT, localtime())
s='%s 发送给我的信息是:%s' %(addr[0],data.decode('utf8'))
tcpClientSock.send(s.encode('utf8'))
print([stime], ':', data.decode('utf8'))
#如果输入 quit(忽略大小写), 则程序退出
STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
if STOP_CHAT:
break
tcpClientSock.close()
sock.close()
Client:
#-*- coding: utf-8 -*- from socket import *class TcpClient:
#测试,连接本机
HOST='127.0.0.1'
#设置侦听端口
PORT=1122
BUFSIZ=1024
ADDR=(HOST, PORT)
def init(self):
self.client=socket(AF_INET, SOCK_STREAM)
self.client.connect(self.ADDR)</span><span style="color: rgba(0, 0, 255, 1)">while</span><span style="color: rgba(0, 0, 0, 1)"> True: data</span>=input(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">></span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> data: </span><span style="color: rgba(0, 0, 255, 1)">break</span> <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">python3传递的是bytes,所以要编码</span> self.client.send(data.encode(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)) </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">发送信息到%s:%s</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">(self.HOST,data)) </span><span style="color: rgba(0, 0, 255, 1)">if</span> data.upper()==<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">QUIT</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">: </span><span style="color: rgba(0, 0, 255, 1)">break</span><span style="color: rgba(0, 0, 0, 1)"> data</span>=<span style="color: rgba(0, 0, 0, 1)">self.client.recv(self.BUFSIZ) </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> data: </span><span style="color: rgba(0, 0, 255, 1)">break</span> <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">从%s收到信息:%s</span><span style="color: rgba(128, 0, 0, 1)">'</span> %(self.HOST,data.decode(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)))
if name == 'main':
client=TcpClient()
注:以上代码为 Python3。