标签:coding [1] accept sock ISE cep for cli add
TCP传输控制协议 稳定,相对于UDP而言要慢一些,Web服务器都是使用TCP
UDP用户数据包协议 不稳定
TCP客户端与服务端的连接
# client.py from socket import * clientSocket = socket(AF_INET,SOCK_STREAM) clientSocket.connect(("192.168.52.1",8897)) while True: user = input("请输入用户名:") clientSocket.sendall(user.encode()) passwd = input("请输入密码:") clientSocket.sendall(passwd.encode()) serdata1 = clientSocket.recv(1024) print(str(serdata1, "utf8")) serdata2 = clientSocket.recv(1024) if (serdata2): while True: data = input("你可以进行以下操作:1.增加用户2.删除用户3.修改用户>>>") clientSocket.sendall(data.encode()) if data == ‘1‘: newuser = input ("请输入要创建的用户名:") newpasswd = input("请输入创建用户的密码:") newstr = newuser + ‘ ‘ + newpasswd clientSocket.sendall(newstr.encode()) serdata3 = clientSocket.recv(1024) print(str(serdata3, "utf8")) elif data == ‘2‘: deluser = input("请输入要删除的用户名:") clientSocket.sendall(deluser.encode()) serdata4 = clientSocket.recv(1024) print(str(serdata4, "utf8")) elif data == ‘3‘: reuser = input("请输入要修改的用户名:") clientSocket.sendall(reuser.encode()) repasswd = input("请输入修改后的密码:") clientSocket.sendall(repasswd.encode()) serdata5 = clientSocket.recv(1024) print(str(serdata5, "utf8")) else: break clientSocket.close()
# server.py
from socket import *
ip_port=("",8897)
serSocket = socket(AF_INET,SOCK_STREAM)
serSocket.bind(ip_port)
serSocket.listen(5)
num = open(‘data.txt‘,‘a+‘,encoding = ‘utf-8‘)
num.seek(0)
fileWords = num.read().split()
while True:
newSocket,address = serSocket.accept()
while True:
recvData1 = newSocket.recv(1024).decode()
if fileWords[0] == recvData1:
recvData2 = newSocket.recv(1024).decode()
if fileWords[1] == recvData2:
server_response = ("登陆成功\n")
newSocket.sendall(bytes(server_response, "utf8"))
i = 1
else:
server_response = ("密码错误")
newSocket.sendall(bytes(server_response, "utf8"))
i = 0
else:
recvData2 = newSocket.recv(1024).decode()
server_response = ("用户名错误")
newSocket.sendall(bytes(server_response, "utf8"))
i =0
if(i):
serve = ("True")
newSocket.sendall(bytes(serve, "utf8"))
Data = newSocket.recv(1024).decode()
if Data == ‘1‘:
newline = newSocket.recv(1024).decode()
num.write(‘\n‘ + newline)
num.close()
print(str(num))
resop = ("创建成功")
newSocket.sendall(bytes(resop,"utf8"))
elif Data == ‘2‘:
deluser = newSocket.recv(1024).decode()
a = (fileWords.index(deluser))
del fileWords[a]
del fileWords[a]
print(fileWords)
file = open(‘data.txt‘, ‘w‘)
for i in fileWords:
file.write(i)
file.write(" ")
file.close()
resop = ("删除成功")
newSocket.sendall(bytes(resop, "utf8"))
elif Data == ‘3‘:
reviseuser = newSocket.recv(1024).decode()
a = (fileWords.index(reviseuser))
repasswd = newSocket.recv(1024).decode()
fileWords[a+1] = repasswd
print(fileWords)
file = open(‘data.txt‘, ‘w‘)
for i in fileWords:
file.write(i)
file.write(" ")
file.close()
resop = ("修改成功")
newSocket.sendall(bytes(resop, "utf8"))
newSocket.close()
serSocket.close()
标签:coding [1] accept sock ISE cep for cli add
原文地址:https://www.cnblogs.com/levelstrcpy/p/8870796.html