代码
day 27 socket
代码
1 socket
import socket
sk = socket.socket()
sk.bind(('127.0.0.1' ,9002 ))
sk.listen()
conn,addr = sk.accept()
conn.send(b'hello' )
msg = conn.recv(1024 )
print (msg.decode('utf-8' ),addr)
conn.close()
sk.close()
client
import socket
sk = socket.socket()
sk.connect(('127.0.0.1' ,9002 ))
msg = sk.recv(1024 )
print (msg)
sk.send(b'wahaha' )
sk.close()
day28 udp
tcp(两个client)
import socket
sk = socket.socket()
sk.bind(('127.0.0.1' ,9001 ))
sk.listen()
while True :
conn,addr = sk.accept()
while True :
msg = input ('>>>' )
conn.send(msg.encode('utf-8' ))
if msg.upper() == 'Q' :
break
content = conn.recv(1024 ).decode('utf-8' )
if content.upper() == 'Q' : break
print (content)
conn.close()
sk.close()
import socket
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
while True :
ret = sk.recv(1024 ).decode('utf-8' )
if ret.upper() == 'Q' :break
print (ret)
msg = input ('>>>' )
sk.send(msg.encode('utf-8' ))
if msg.upper() == 'Q' :
break
sk.close()
udp(两个client)
import socket
sk = socket.socket(type =socket.SOCK_DGRAM)
sk.bind(('127.0.0.1' ,9001 ))
while True :
msg,client_addr = sk.recvfrom(1024 )
print (msg.decode('utf-8' ))
content = input ('>>>' )
sk.sendto(content.encode('utf-8' ),client_addr)
sk.close()
import socket
sk = socket.socket(type =socket.SOCK_DGRAM)
server_addr = ('127.0.0.1' ,9001 )
while True :
content = input ('>>>' )
if content.upper() == 'Q' :break
sk.sendto(content.encode('utf-8' ),server_addr)
msg = sk.recv(1024 ).decode('utf-8' )
if msg.upper() == 'Q' :break
print (msg)
sk.close()
day29
一对多聊天(两个client)
import json
import socket
sk = socket.socket(type =socket.SOCK_DGRAM)
sk.bind(('127.0.0.1' ,9001 ))
user_info = {
1234 :('alex' ,'\033[1;32m' ),
5678 :('宝元' ,'\033[1;31m' ),
}
while True :
msg,addr = sk.recvfrom(1024 )
str_msg = msg.decode('utf-8' )
dic_msg = json.loads(str_msg)
code = dic_msg['code' ]
content = dic_msg['msg' ]
print ('%s%s : %s\033[0m' %(user_info[code][1 ],user_info[code][0 ],content))
ret = input ('>>>' ).encode('utf-8' )
sk.sendto(ret,addr)
sk.close()
import json
import socket
sk = socket.socket(type =socket.SOCK_DGRAM)
addr = ('127.0.0.1' ,9001 )
code = 5678
while True :
msg = input ('>>>' )
if msg.upper() == 'Q' : break
send_msg = {'code' :code,'msg' :msg}
str_msg = json.dumps(send_msg)
sk.sendto(str_msg.encode('utf-8' ),addr)
ret = sk.recv(1024 ).decode('utf-8' )
if ret.upper() == 'Q' : break
print (ret)
sk.close()
登录
import json
import socket
sk = socket.socket(type =socket.SOCK_DGRAM)
addr = ('127.0.0.1' ,9001 )
code = 5678
while True :
msg = input ('>>>' )
if msg.upper() == 'Q' : break
send_msg = {'code' :code,'msg' :msg}
str_msg = json.dumps(send_msg)
sk.sendto(str_msg.encode('utf-8' ),addr)
ret = sk.recv(1024 ).decode('utf-8' )
if ret.upper() == 'Q' : break
print (ret)
sk.close()
import json
import socket
username = input ('用户名 :' )
password = input ('密 码 :' )
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
msg = {'operate' :'login' ,
'user' :username,
'pwd' :password}
str_msg = json.dumps(msg)
sk.send(str_msg.encode('utf-8' ))
content = sk.recv(1024 )
str_content = content.decode('utf-8' )
dic_content = json.loads(str_content)
if dic_content['result' ]:
print ('登录成功' )
else :
print ('登录失败' )
sk.close()
alex|ee838c58e5bb3c9e687065edd0ec454f
登录2
import sys
import json
import socket
import hashlib
def get_md5 (username,password ):
md5 = hashlib.md5(username.encode('utf-8' ))
md5.update(password.encode('utf-8' ))
return md5.hexdigest()
def login (dic_msg ):
print (dic_msg['user' ], dic_msg['pwd' ])
with open ('userinfo' , encoding='utf-8' ) as f:
for line in f:
user, pwd = line.strip().split('|' )
print (pwd,get_md5(dic_msg['user' ], dic_msg['pwd' ]))
if user == dic_msg['user' ] and pwd == get_md5(dic_msg['user' ], dic_msg['pwd' ]):
return {'opt' :'login' , 'result' :True }
else :return {'opt' :'login' , 'result' :False }
sk= socket.socket()
sk.bind(('127.0.0.1' ,9001 ))
sk.listen()
while True :
conn,addr = sk.accept()
msg = conn.recv(1024 ).decode('utf-8' )
dic_msg = json.loads(msg)
if hasattr (sys.modules[__name__],dic_msg['operate' ]):
ret = getattr (sys.modules[__name__],dic_msg['operate' ])(dic_msg)
content = json.dumps(ret).encode('utf-8' )
conn.send(content)
conn.close()
sk.close()
import json
import socket
import hashlib
def get_md5 (username,password ):
md5 = hashlib.md5(username[::2 ].encode('utf-8' ))
md5.update(password.encode('utf-8' ))
return md5.hexdigest()
username = input ('用户名 :' )
password = input ('密 码 :' )
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
msg = {'operate' :'login' ,
'user' :username,
'pwd' :get_md5(username,password)}
str_msg = json.dumps(msg)
sk.send(str_msg.encode('utf-8' ))
content = sk.recv(1024 )
str_content = content.decode('utf-8' )
dic_content = json.loads(str_content)
if dic_content['result' ]:
print ('登录成功' )
else :
print ('登录失败' )
sk.close()
黏包sever/client
import json
import struct
import socket
sk = socket.socket()
sk.bind(('127.0.0.1' ,9001 ))
sk.listen()
conn,addr = sk.accept()
num = conn.recv(4 )
num = struct.unpack('i' , num)[0 ]
str_dic = conn.recv(num).decode('utf-8' )
dic = json.loads(str_dic)
with open (dic['filename' ],'wb' ) as f:
content = conn.recv(dic['filesize' ])
f.write(content)
conn.close()
sk.close()
import os
import json
import struct
import socket
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
filepath = input ('请输入文件路径 :' )
filename = os.path.basename(filepath)
filesize = os.path.getsize(filepath)
dic = {'filename' :filename,'filesize' :filesize}
str_dic = json.dumps(dic)
bytes_dic = str_dic.encode('utf-8' )
len_dic = len (bytes_dic)
bytes_len = struct.pack('i' ,len_dic)
sk.send(bytes_len)
sk.send(bytes_dic)
with open (filepath,'rb' ) as f:
content = f.read()
sk.send(content)
sk.close()
黏包现象
import struct
import socket
sk = socket.socket()
sk.bind(('127.0.0.1' ,9001 ))
sk.listen()
conn,addr = sk.accept()
str_msg = 'hello,你好么'
byets_msg = str_msg.encode('utf-8' )
num = len (byets_msg)
len_bytes = struct.pack('i' ,num)
conn.send(len_bytes)
conn.send(byets_msg)
conn.send(b'world' )
conn.close()
sk.close()
import time
import struct
import socket
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
time.sleep(0.1 )
num= sk.recv(4 )
num = struct.unpack('i' ,num)[0 ]
msg2 = sk.recv(num)
print (msg2.decode('utf-8' ))
print (sk.recv(1024 ))
sk.close()
day30
并发的socketserver(两个client)
import time
import socketserver
class Myserver (socketserver.BaseRequestHandler):
def handle (self ):
conn = self.request
for i in range (200 ):
conn.send(('hello%s' %i).encode('utf-8' ))
print (conn.recv(1024 ))
time.sleep(0.5 )
server = socketserver.ThreadingTCPServer(('127.0.0.1' ,9001 ),Myserver)
server.serve_forever()
import socket
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
while True :
msg = sk.recv(1024 )
print (msg)
sk.send(b'byebye' )
sk.close()
验证客户端的合法性
hmac模块
import os
import hmac
hmac = hmac.new(b'alex sb' ,os.urandom(32 ))
print (hmac.digest())
验证
import os
import hashlib
import socket
secret_key = b'alex sb'
sk = socket.socket()
sk.bind(('127.0.0.1' ,9001 ))
sk.listen()
conn,addr = sk.accept()
rand = os.urandom(32 )
conn.send(rand)
sha = hashlib.sha1(secret_key)
sha.update(rand)
res = sha.hexdigest()
ret = conn.recv(1024 ).decode('utf-8' )
if ret == res:
print ('是合法的客户端' )
else :
print ('不是合法的客户端' )
conn.close()
import socket
import hashlib
secret_key = b'alexsb'
sk = socket.socket()
sk.connect(('127.0.0.1' ,9001 ))
rand = sk.recv(32 )
sha = hashlib.sha1(secret_key)
sha.update(rand)
res = sha.hexdigest()
sk.send(res.encode('utf-8' ))
sk.close()
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 不到万不得已,千万不要去外包
· C# WebAPI 插件热插拔(持续更新中)
· 会议真的有必要吗?我们产品开发9年了,但从来没开过会
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 如何打造一个高并发系统?