简体   繁体   English

连接被拒绝错误Python

[英]Connection refused error Python

I'm using python on Mac and for some reason the connection is being refused when I try to run the server. 我在Mac上使用python,由于某种原因,当我尝试运行服务器时,连接被拒绝。 Here is the code for both the Client and Server. 这是客户端和服务器的代码。 I am trying to make it so that the user can login to a login system through the client side. 我正在尝试使用户可以通过客户端登录到登录系统。 I also wish to be able to make it so that when the user log's into an account their password is automatically saved to a .txt document. 我也希望能够做到这一点,以便当用户登录到帐户时,其密码会自动保存到.txt文档中。 Anyone know how i can do this? 有人知道我该怎么做吗? Thanks for reading. 谢谢阅读。

Client code: 客户代码:

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()

server code: 服务器代码:

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") 

Open the two programs in separate shell. 在单独的外壳中打开两个程序。
First run server program. 首先运行服务器程序。
Then run your client program while the server program is still running. 然后在服务器程序仍在运行时运行客户端程序。

It will solve the connection refused error. 它将解决连接被拒绝的错误。
Let me know if it worked:) 让我知道它是否有效:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM