简体   繁体   English

重用相同的套接字进行发送和接收(Python)

[英]Reuse the same socket to send and receive (Python)

I have written a simple script to send and receive messages using the Python socket module. 我编写了一个简单的脚本来使用Python套接字模块发送和接收消息。 I want to first send a message using sendMsg and then receive a response using listen . 我想首先使用sendMsg发送消息,然后使用listen接收响应。 sendMsg works fine but when my server sends a response I receive the error: sendMsg工作正常,但是当我的服务器发送响应时,我收到错误消息:

"[WinError 10038] An operation was attempted on something that is not a socket" “ [WinError 10038]尝试对非套接字的对象进行操作”

I close the socket connection in sendMsg and then try to bind it in listen , but it's at this line that the error is produced. 我在sendMsg关闭了套接字连接,然后尝试在listen绑定它,但正是在这一行产生了错误。 Please could someone show me what I am doing wrong! 请有人告诉我我做错了!

import socket

port = 3400
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), port))

def sendMsg():

    print("\nSending message:\n\n")
    msg = ("Sample text").encode("utf-8")
    s.send(msg)
    s.close()

def listen():

    s.bind(("", port))
    s.listen(1)

    serverSocket, info = s.accept()
    print("Connection from", info, "\n")
    while 1:
        try:            
            buf = bytearray(4000)
            view = memoryview(buf)
            bytes = serverSocket.recv_into(view, 4000)
            if bytes:
                stx = view[0]
                Size = view[1:3]
                bSize = Size.tobytes()
                nTuple = struct.unpack(">H", bSize)
                nSize = nTuple[0]
                message = view[0:3+nSize]
                messageString = message.tobytes().decode("utf-8").strip()
                messageString = messageString.replace("\x00", "")
            else:
                break
        except socket.timeout:
            print("Socket timeout.")
            break

sendMsg()

listen()

Note: I have implemented listen in a separate client and used the line 注意:我已经在一个单独的客户端中实现了listen ,并使用了

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 3)

before s.bind() and s.connect() . s.bind()s.connect() This works OK. 这样就可以了。 It would be nice to have it all in one client though. 最好将所有这些都放在一个客户端中。

As per the docs the socket.close() will close the socket and no further operations are allowed on it. 根据文档, socket.close()将关闭套接字,并且不允许对其进行进一步的操作。

So in your code this line s.close() is closing the socket. 因此,在您的代码中,此行s.close()正在关闭套接字。

Because of that the s.bind(("", port)) will not work as the socket s is already closed! 因此, s.bind(("", port))将不起作用,因为套接字s已经关闭!

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

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