sock实现通讯(TCP)
sock实现通讯(TCP)
单次单用户通讯
#server端
import socket
sk = socket.socket() #买手机
sk.bind(("127.0.0.1",9000)) #绑定手机号,或者本机ip
sk.listen() #开机
conn,addr = sk.accept() #等着接电话
conn.send(b"hello") #发送内容
msg = conn.recv(1024) #所最大接受字符为1024
print(msg)
conn.close() #挂电话,连接关闭
sk.close() #关机
#clinet端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
msg = sk.recv(1024) #接受
print(msg) #呈现接受的内容
sk.send(b"byebye") #发送的 内容
sk.close()
socket(套接字)
- 工作在应用层和传输层之间的抽象层
- 帮助我们完成了所有信息的组织和拼接
- sokcet对于程序员来说,已经是网络操作的底层
多次单用户通讯
#sever端
import socket
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen()
print("*"*20)
conn,addr = sk.accept() #阻塞
while True:
msg = conn.recv(1024).decode("utf-8")
print(msg)
if msg.upper() == "Q":break
inp = input(">>>")
conn.send(inp.encode("utf-8"))
if inp.upper() == "Q":
break
conn.close()
sk.close()
#cilnet端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
inp = input(">>>")
sk.send(inp.encode("utf-8"))
if inp.upper() == "Q":break
msg = sk.recv(1024).decode("utf-8")
if msg.upper() == "Q":break
print(msg)
sk.close()
多次多用户通讯
#sever端
import socket
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen()
print("*"*20)
while True:
conn,addr = sk.accept() #阻塞
while True:
msg = conn.recv(1024).decode("utf-8")
print(msg)
if msg.upper() == "Q":break
inp = input(">>>")
conn.send(inp.encode("utf-8"))
if inp.upper() == "Q":
break
conn.close()
sk.close()
#client1端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
inp = input(">>>")
sk.send(inp.encode("utf-8"))
if inp.upper() == "Q":break
msg = sk.recv(1024).decode("utf-8")
if msg.upper() == "Q":break
print(msg)
sk.close()
#client2端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
inp = input(">>>")
sk.send(inp.encode("utf-8"))
if inp.upper() == "Q":break
msg = sk.recv(1024).decode("utf-8")
if msg.upper() == "Q":break
print(msg)
sk.close()
带身份带颜色变换的无限多用户通讯
#sever端
import socket
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen(5) #n允许多少客户端等待
print("*"*20)
while True:
conn,addr = sk.accept() #阻塞
while True:
msg = conn.recv(1024).decode("utf-8")
print("\033[0;31m%s\033[0m" % msg)
if msg.upper() == "Q":break
inp = input("服务器:")
conn.send(("服务器:"+inp).encode("utf-8"))
if inp.upper() == "Q":
break
conn.close()
sk.close()
#client1端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
inp = input("小杨:")
sk.send(("小杨:"+inp).encode("utf-8"))
if inp.upper() == "Q":break
msg = sk.recv(1024).decode("utf-8")
if msg.upper() == "Q":break
print("\033[0;34m%s\033[0m" % msg)
sk.close()
#client2端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
inp = input("小李:")
sk.send(("小李"+inp).encode("utf-8"))
if inp.upper() == "Q":break
msg = sk.recv(1024).decode("utf-8")
if msg.upper() == "Q":break
print(msg)
sk.close()
-
TCP通讯练习
#改变字体颜色,以及绑定识别用户的信息和昵称 #server端 import socket import json sk = socket.socket() sk.bind(("127.0.0.1",9000)) sk.listen() color_dic = { "12345":{"color":"\033[32m","name":"alex"}, "12346":{"color":"\033[32m","name":"wusir"}, "12347":{"color":"\033[32m","name":"xiaoyang"} } conn,_= sk.accept() #阻塞 while True: msg = conn.recv(1024).decode("utf-8") dick_msg = json.loads(msg) uid = dick_msg["id"] if dick_msg["msg"].upper() == "Q": print("%s已经下线"%color_dic[uid]["color"]) print('%s%s:%s\033[0m'%(color_dic[uid]["color"],color_dic[uid]["name"],dick_msg["msg"])) inp = input(">>>") conn.send(inp.encode("utf-8")) if inp.upper() == "Q": print("你已断开与%s的聊天"%(color_dic[uid]["name"])) break conn.close() sk.close() #clinet端 import socket import json sk = socket.socket() sk.connect(("127.0.0.1",9000)) id = "12345" while True: inp = input(">>>") dic = {"msg":inp,"id":id} str_dic = json.dumps(dic) sk.send(str_dic.encode("utf-8")) if inp.upper() == "Q": print("你已断开和server的聊天") msg = sk.recv(1024).decode("utf-8") if msg.upper() == "Q":break print(msg) sk.close()
基于TCP加密通讯处理
#server端
import json
import socket
import hashlib
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen()
def get_md5(username,password):
md5 = hashlib.md5(username.encode("utf-8")) #动态加盐
md5.update(password.encode("utf-8")) #哈希运算
return md5.hexdigest()
conn,_ = sk.accept()
str_dic = conn.recv(1024).decode("utf-8")
dic = json.loads(str_dic)
with open("userinfo",encoding="utf-8")as f:
for line in f:
user, passwd = line.strip().split("|")
if user == dic["usr"] and passwd == get_md5(dic["usr"],dic["pwd"]):
res_dic = {"opt":"login","result":True}
break
else:
res_dic = {"opt":"login","result":False}
sdic = json.dumps(res_dic)
conn.send(sdic.encode("utf-8"))
conn.close()
sk.close()
#userinfo
alex|431149301c8792c1ab4c40b783d37100 #经过哈希运算的密码
#client端
import socket
import json
user = input("username:")
pwd = input("password:")
dic = {"usr":user,"pwd":pwd}
str_dic = json.dumps(dic)
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
sk.send(str_dic.encode("utf-8"))
ret = sk.recv(1024).decode("utf-8")
ret_dic = json.loads(ret)
if ret_dic["result"]:
print("登录成功")
else:
print("登录失败")
sk.close()
基于TCP文件传输
#client端
import socket
import os
import json
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
file_path = input(">>>")
if os.path.isabs(file_path): #判断是否为绝对路径
filename = os.path.basename(file_path) #获取文件名
filesize = os.path.getsize(file_path) #获取文件的大小,为文件的接受做准备
dic = {"filename":filename,"filesize":filesize} #向服务器传出文件的基本信息
srt_dic = json.dumps(dic)
sk.send(srt_dic.encode("utf-8"))
with open(file_path,mode = "rb")as f:
content = f.read()
sk.send(content)
sk.close()
sk.close()
#server端
import socket
import json
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen()
conn,_ = sk.accept()
str_dic =conn.recv(1024).decode("utf-8")
dic = json.loads(str_dic)
content = conn.recv(dic["filesize"]) #按照文件的大小接受,由于TCP本身的缺陷,文件已损失部分
with open(dic["filename"],mode="wb")as f: #在当前的路径下打开文件
f.write(content) #将接受到信息写入
conn.close()
sk.close()
#补充:文件名的获取
import os
filename = r"C:\Users\lenovo\Desktop\医疗健康领域知识图谱的应用现状与挑战"#裸文件名的时候记得加r
# print(filename)
filename = os.path.basename(filename)
print(filename)
记录学习的点点滴滴