Python ConnectionRefusedError:[WinError 10061]

时间:2019-09-17 13:49:35

标签: python sockets networking

我是python的新手,我想创建一个服务器-客户端应用程序,但是每次尝试连接时,都会看到此错误。 我尝试更改send()和receive()函数的顺序,但是没有解决

msg = client_socket.recv (BUFSIZ) .decode ("utf8")
OSError: [WinError 10038] An attempt was made to perform an operation on an object that is not a socket

这是代码 Client.py

    """Handles receiving of messages."""
    #client_socket.bind((HOST, PORT))
    #client_socket.connect((HOST, PORT))
    msg = client_socket.recv(BUFSIZ).decode("utf8")
    print(msg)
    client_socket.close()


def send(event=None):  # event is passed by binders.
    """Handles sending of messages."""
    client_socket.connect((HOST, PORT))
    msg = input("MSG: ")
    client_socket.send(bytes(msg, "utf8"))
    client_socket.close()

#----Now comes the sockets part----
HOST = '127.0.0.1'
PORT = 7557
if not PORT:
    PORT = 33000
else:
    PORT = int(PORT)

BUFSIZ = 1024
ADDR = (HOST, PORT)

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)

receive_thread = Thread(target=receive)
receive_thread.start()


if __name__ == '__main__':
    client_socket.close()
    receive()
    send()
    receive()

Ps:99%的代码来自互联网

1 个答案:

答案 0 :(得分:1)

接收和发送信息后不要关闭套接字。

from socket import AF_INET, socket, SOCK_STREAM 
from threading import Thread
def receive() :
    """Handles receiving of messages."""
    while True :
        msg = client_socket.recv(BUFSIZ).decode("utf8")
        print(msg)


def send():
    """Handles sending of messages."""
    while True:
        msg = input("MSG: ")
        client_socket.send(bytes(msg, "utf8"))

#----Now comes the sockets part----
HOST = '127.0.0.1'
PORT = 7557
BUFSIZ = 1024
ADDR = (HOST, PORT)

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)

receive_thread = Thread(target=receive, args=() )
send_thread = Thread(target=send, args=()) 



if __name__ == '__main__':
    receive_thread.start()
    send_thread.start()

这是您代码的修改版本。

我自己使用相同的逻辑制作了一个类似的应用程序,看看:

https://github.com/moe-assal/Chatting_Server