客户端到服务器:连接

时间:2020-10-14 21:08:56

标签: python python-3.x server

在python中,我正在创建一个客户端服务器,并且试图连接客户端和服务器。如果client.py在server.py的主机上运行,​​它将连接。但是,如果另一台计算机尝试连接到服务器IP,则它不会连接。

服务器代码:

import socket

IP = "127.0.0.1"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP, 1234))
s.listen(5)

while True:
    # now our endpoint knows about the OTHER endpoint.
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established.")
    clientsocket.send(bytes("Hello","utf-8"))
    clientsocket.close()

客户代码:

import socket


IP = "127.0.0.1"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, 1234))


while True:
    full_msg = ''
    while True:
        msg = s.recv(8)
        if len(msg) <= 0:
            break
        full_msg += msg.decode("utf-8")

    if len(full_msg) > 0:
        print(full_msg)

当我在同一台计算机上运行这两个代码时,它可以连接并正常工作。但是,当我在另一台计算机上运行该代码时,会出现一条错误消息:

Traceback (most recent call last):
  File "D:/PyCharmCode/pythonProject/main.py", line 6, in <module>
    s.connect((IP, 1234))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

0 个答案:

没有答案