我在Mac上使用python,出于某种原因,当我尝试运行服务器时,连接被拒绝了。以下是客户端和服务器的代码。我试图让用户可以通过客户端登录到登录系统。我还希望能够这样做,以便当用户登录帐户时,他们的密码会自动保存到.txt文档中。有谁知道我怎么做到这一点?谢谢阅读。
客户代码:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Waiting for connection")
s.connect(('127.0.0.1', 4000))
data = s.recv(1024).decode()#max number of bytes recv
print ("data from server", data)
message = str(input("Send: ->"))
s.send(message.encode())
s.close()
input("\n\n press enter to close")
users = {}
status = ""
def displayMenu():
status = input("Are you registered user? Please write yes or no. Press q to quit")
if status == "yes":
oldUser()
elif status == "no":
newUser()
def newUser():
createLogin = input("Create login name: ")
if createLogin in users:
print("\nLogin name already exist!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw
print("\nUser created\n")
def oldUser():
login = input("Enter login name: ")
passw = input("Enter password: ")
if login in users and users[login] == passw:
print("\nLogin successful! Your credentials have been saved.\n")
else:
print("\nUser doesn't exist or wrong password!\n")
while status != "q":
displayMenu()
服务器代码:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Listening: ")
s.bind(('127.0.0.1', 4000))
s.listen(10) #listen to 1 connection at a time
c, addr = s.accept()
print ("Connection from: ", addr)
message = input("Send: ->")
c.sendall(message.encode())
data = c.recv(1024).decode()#max number of bytes recv
print("data from client ", data)
c.close()
input("\n\n press enter to close")
答案 0 :(得分:0)
在单独的shell中打开两个程序 首先运行服务器程序 然后在服务器程序仍在运行时运行客户端程序。
它将解决连接拒绝错误 让我知道它是否有效:)