鱼C论坛

 找回密码
 立即注册
查看: 4865|回复: 12

[已解决]WinError 10061 由于目标计算机积极拒绝,无法连接

[复制链接]
发表于 2022-3-17 12:56:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我在尝试用Python做一个聊天室的时候 发现我的电脑上一跑就是  ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。
用的
  1. HOST = '127.0.0.1'
  2. PORT = 13502
复制代码



所以我尝试从网上下了别人的代码   发现也会报这个错
想知道这是我设置不对的原因还是什么其他因素导致的。 有什么办法解决嘛?


已经尝试过internet 属性 的局域网设置自动检测  没有解决。
最佳答案
2022-3-17 14:19:19

我知道你哪里错了,你那个目标计算机拒绝确实是因为你的服务端关掉了,

我试了一下如果你的客户端什么都没有输入就按回车的话就会导致服务端崩掉,

你客户端随便输点东西再回车

跑project-main

跑project-main

sever_user

sever_user

CS4850-Project-main.zip

4.97 KB, 下载次数: 2

1

sever_user.zip

3.74 KB, 下载次数: 3

2

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-3-17 13:00:44 | 显示全部楼层
project-main code:
server.py
  1. import socket
  2. import csv
  3. from User import User
  4. import pickle

  5. HOST = '127.0.0.1'  
  6. PORT = 18737        



  7. def checkFunction(conn, data):
  8.     #decode byte data and split the string into parts
  9.     data = data.decode('utf-8')
  10.     command = data.split()
  11.     if command[0] == "newuser":
  12.         #call funct to check if user already exists
  13.         result = checkUserExists(command[1])
  14.         if result == True:
  15.             #if user does not exist call funct to create the new user
  16.             newUser(conn,command[1], command[2])
  17.         elif result == False:
  18.             error = "Denied. User account already exists."
  19.             conn.send(bytes(error,'utf-8'))
  20.     elif command[0] == "login":
  21.         #call login funct
  22.         result = login(conn, command[1], command[2])
  23.         if result == True:
  24.             updateUserState(command[1], True)
  25.             #get User obj and put in pickle to send to client
  26.             logged = getUser(command[1])
  27.             logged = pickle.dumps(logged)
  28.             #header string to indicate login success to client
  29.             header = bytes("login",'utf-8')
  30.             #send header and userObj pickle to client
  31.             conn.send(header + logged)
  32.         elif result == False:
  33.             conn.send(bytes("Denied. Username or password incorrect",'utf-8'))
  34.     elif command[0] == "send":
  35.         #split send command into 3 parts (2 spaces) (send,username,message content)
  36.         command = data.split(" ", 2)
  37.         #msg create and print to server
  38.         msg = command[1] + ": " + command[2]
  39.         print(msg)
  40.         #send msg to client
  41.         conn.send(bytes(msg,'utf-8'))
  42.     elif command[0] == "logout":
  43.         #make sure user can be logged out
  44.         updateUserState(command[1], True)
  45.         result = getUserState(command[1])
  46.         if result == True:
  47.             #make user logged in state false
  48.             updateUserState(command[1], False)
  49.             #msg and print to server
  50.             msg = command[1] + " logout"
  51.             print(msg)
  52.             #send logout msg to client
  53.             conn.send(bytes(command[1] + " left",'utf-8'))
  54.         elif result == False:
  55.             error = "Denied. Please login first"
  56.     elif command[0] == "retry":
  57.         #response for if no user is logged in
  58.         conn.send(bytes("retrying",'utf-8'))


  59. def checkUserExists(user):
  60.     #iterate over users in array to check if the user exists
  61.     for name in users:
  62.         username = name.username
  63.         if username == user:
  64.             #user already exists
  65.             return False
  66.    
  67.     return True
  68.         

  69. #func to put a new user into the users.txt file
  70. def newUser(conn,username,passw):
  71.     #open the file and format the new user entry
  72.     File = open("users.txt", "a")
  73.     entry = "\n(" + username + ", " + passw + ")"
  74.     #add the new entry to the User list
  75.     users.append(User(username, False))
  76.     #add the entry on a newline to the file
  77.     File.write(entry)
  78.     File.close()
  79.     #report success
  80.     success = "New user account created. Please login."
  81.     print("New user account created.")
  82.     conn.send(bytes(success,'utf-8'))


  83. #func to login a user
  84. def login(conn,user,passw):
  85.     #open the users file
  86.     File = open("users.txt", "r")
  87.     #iterate over users in the file, use csv to access parts of the entries
  88.     reader = csv.reader(File, delimiter=',')
  89.     for row in reader:
  90.         #get a username entry
  91.         username = row[0]
  92.         #remove parenthesis
  93.         username = username[1:]
  94.         #compare user entered username with username in file
  95.         if username == user:
  96.             #if matched, get the password for the user
  97.             recordPass = row[1]
  98.             #remove parenthesis
  99.             recordPass = recordPass[:-1]
  100.             #remove leading space
  101.             recordPass = recordPass[1:]
  102.             #compare passwords
  103.             if recordPass == passw:
  104.                 print(username, "login.")
  105.                 return True
  106.     File.close()
  107.     return False


  108. #func to change user logged in status
  109. def updateUserState(user, state):
  110.     for name in users:
  111.         username = name.username
  112.         if username == user:
  113.             name.logStatus = state


  114. #func to get logged in state of user
  115. def getUserState(user):
  116.     for name in users:
  117.         username = name.username
  118.         if username == user:
  119.             return name.logStatus


  120. #get a specific User obj
  121. def getUser(user):
  122.     for name in users:
  123.         username = name.username
  124.         if username == user:
  125.             return name


  126. #create the User obj list
  127. def usersInit():
  128.     users = []
  129.     #open users file
  130.     File = open("users.txt", "r")
  131.     reader = csv.reader(File, delimiter=',')
  132.     #read in usernames
  133.     for row in reader:
  134.         username = row[0]
  135.         username = username[1:]
  136.         #create new Users with the usernames in the file
  137.         users.append(User(username,False))
  138.     File.close()
  139.     return users


  140. print("My chat room server. Version one.")

  141. while True:
  142.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  143.         s.bind((HOST, PORT))
  144.         s.listen()
  145.         conn, addr = s.accept()
  146.         with conn:
  147.             data = conn.recv(1024)
  148.             #initiate a list of all users
  149.             users = usersInit()
  150.             #send data from client to function to figure out what to do
  151.             checkFunction(conn,data)
  152.             conn.sendall(data)
复制代码

client.py:
  1. import socket
  2. import pickle
  3. from User import User


  4. HOST = '127.0.0.1'
  5. PORT = 18737        # The port used by the server

  6. print("My chat room client. Version One.\n")

  7. userLogged = User("init",False)

  8. while True:
  9.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  10.         s.connect((HOST, PORT))
  11.         #get user input
  12.         command = input()
  13.         #split user input into parts on spaces
  14.         commandParts = command.split()

  15.         #if statement to check for login, logout, and send commands
  16.         if commandParts[0] == "login":
  17.             #check for proper command usage
  18.             if len(commandParts) == 3:
  19.                 #send login command to server
  20.                 s.send(bytes(command,'utf-8'))
  21.                 #receive response from server
  22.                
  23.                 response = s.recv(1024)
  24.                 #decode header bytes
  25.                 result = response[:5]
  26.                 result = result.decode('utf-8')
  27.                 if result == "login":
  28.                     #if header bytes match, get the user pickle
  29.                     userObj = response[5:]
  30.                     #unpickle User
  31.                     userLogged = pickle.loads(userObj)
  32.                     print("login confirmed")
  33.                 else:
  34.                     #header bytes dont match, print error response
  35.                     print(response.decode('utf-8'))
  36.                
  37.             else:
  38.                 print("Command usage: login <user> <pass>")
  39.                 s.send(bytes("retry",'utf-8'))
  40.                 response = s.recv(1024)
  41.                 response = response.decode('utf-8')
  42.         elif commandParts[0] == "logout":
  43.             #check for proper command usage
  44.             if len(commandParts) == 1:
  45.             #make sure a user is logged in
  46.                 if userLogged and userLogged.logStatus == True:
  47.                 #use User object to tell the server which user to logout
  48.                     msg = commandParts[0] + " " + userLogged.username
  49.                     s.send(bytes(msg,'utf-8'))
  50.                     response = s.recv(1024)
  51.                     #get logout response and close socket connection
  52.                     response = response.decode('utf-8')
  53.                     print(response)
  54.                     s.close
  55.                     break
  56.                 else:
  57.                     #handle if no user is logged in
  58.                     print("Denied. Please login first.")
  59.                     command = "retry"
  60.                     s.send(bytes(command,'utf-8'))
  61.                     response = s.recv(1024)
  62.                     response = response.decode('utf-8')
  63.             else:
  64.                 print("Command usage: logout")
  65.                 command = "retry"
  66.                 s.send(bytes(command,'utf-8'))
  67.                 response = s.recv(1024)
  68.                 response = response.decode('utf-8')
  69.         elif commandParts[0] == "send":
  70.             #make sure a user is logged in
  71.             if userLogged and userLogged.logStatus == True:
  72.                 #split the send command to keep the message content together
  73.                 sendMsg = command.split(" ", 1)
  74.                 #check for proper send usage
  75.                 if len(sendMsg) == 2 and sendMsg[0] == "send":
  76.                     #insert the username into the command to send to the server
  77.                     sendMsg.insert(1,userLogged.username)
  78.                     sendStr = ""
  79.                     #put the send command together and send to server
  80.                     for ele in sendMsg:
  81.                         sendStr += ele + " "
  82.                     s.send(bytes(sendStr,'utf-8'))
  83.                     response = s.recv(1024)
  84.                     response = response.decode('utf-8')
  85.                     print(response)
  86.                 else:
  87.                     print("Command usage: send <message>")
  88.                     command = "retry"
  89.                     s.send(bytes(command,'utf-8'))
  90.                     response = s.recv(1024)
  91.                     response = response.decode('utf-8')
  92.             else:
  93.                 #handle if no user is logged in
  94.                 print("Denied. Please login first.")
  95.                 command = "retry"
  96.                 s.send(bytes(command,'utf-8'))
  97.                 response = s.recv(1024)
  98.                 response = response.decode('utf-8')
  99.         elif commandParts[0] == "newuser":
  100.             #check for proper newuser usage
  101.             if len(commandParts) == 3:
  102.                 s.send(bytes(command,'utf-8'))
  103.                 response = s.recv(1024)
  104.                 response = response.decode('utf-8')
  105.                 print(response)
  106.             else:
  107.                 print("Command usage: newuser <username> <password>")
  108.                 command = "retry"
  109.                 s.send(bytes(command,'utf-8'))
  110.                 response = s.recv(1024)
  111.                 response = response.decode('utf-8')
  112.         else:
  113.             #catch invalid commands
  114.             print("Invalid Command. Potential commands are:")
  115.             if userLogged.logStatus == True:
  116.                 print("send <message>\nlogout")
  117.             elif userLogged.logStatus == False:
  118.                 print("newuser <username> <password>\nlogin <username> <password>")
  119.             command = "retry"
  120.             s.send(bytes(command,'utf-8'))
  121.             response = s.recv(1024)
  122.             response = response.decode('utf-8')
  123.             
  124.         
复制代码

User.py:
  1. class User:
  2.     def __init__(self,username,logStatus):
  3.         self.username = username
  4.         self.logStatus = logStatus
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-17 13:03:39 | 显示全部楼层
请先执行 server.py 再执行 client.py
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 13:07:39 | 显示全部楼层
isdkz 发表于 2022-3-17 13:03
请先执行 server.py 再执行 client.py

我就是这样操作的但还是会报错

=========== RESTART: D:\学习\CS 4850\online code\CS4850-Project-main\server.py ===========
My chat room server. Version one.

=========== RESTART: D:\学习\CS 4850\online code\CS4850-Project-main\client.py ===========
My chat room client. Version One.

Traceback (most recent call last):
  File "D:\学习\CS 4850\online code\CS4850-Project-main\client.py", line 22, in <module>
    s.connect((HOST, PORT))
ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-17 13:09:35 | 显示全部楼层
本帖最后由 isdkz 于 2022-3-17 13:11 编辑
FlandRem 发表于 2022-3-17 13:07
我就是这样操作的但还是会报错

=========== RESTART: D:\学习\CS 4850\online code\CS4850-Project-ma ...


你是在同一台电脑执行的吗?不要把 server.py 关掉,建议不要用 idle,

你打开你的源代码所在的文件夹,然后在地址栏输入 cmd,

这样执行(在两个不同的cmd下):
  1. python server.py
复制代码

  1. python client.py
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 13:19:09 | 显示全部楼层
isdkz 发表于 2022-3-17 13:09
你是在同一台电脑执行的吗?不要把 server.py 关掉,建议不要用 idle,

你打开你的源代码所在的文件 ...

还是会报错
WeChat Screenshot_20220317001746.png
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-17 13:21:09 | 显示全部楼层

你的代码中 HOST 和 PORT 分别是什么?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 13:22:34 | 显示全部楼层
  1. HOST = '127.0.0.1'
  2. PORT = 13502
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 14:11:15 | 显示全部楼层
isdkz 发表于 2022-3-17 13:21
你的代码中 HOST 和 PORT 分别是什么?
  1. HOST = '127.0.0.1'
  2. PORT = 13502
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-17 14:12:27 | 显示全部楼层

client 的跟 server 的一样吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 14:13:26 | 显示全部楼层
isdkz 发表于 2022-3-17 14:12
client 的跟 server 的一样吗?

对的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-17 14:19:19 | 显示全部楼层    本楼为最佳答案   

我知道你哪里错了,你那个目标计算机拒绝确实是因为你的服务端关掉了,

我试了一下如果你的客户端什么都没有输入就按回车的话就会导致服务端崩掉,

你客户端随便输点东西再回车
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-3-17 14:23:18 | 显示全部楼层
isdkz 发表于 2022-3-17 14:19
我知道你哪里错了,你那个目标计算机拒绝确实是因为你的服务端关掉了,

我试了一下如果你的客户端什么 ...

谢谢大佬   终于解决了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-6 04:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表