客户端发送消息后服务端报错OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。

来源:3-2 socket非阻塞模块1

weixin_慕沐8459239

2019-05-08 11:46

# 错误详情

Traceback (most recent call last):

nihao

  File "C:\Users\34565\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 625, in process_request_thread

----------------------------------------

    self.finish_request(request, client_address)

Exception happened during processing of request from ('127.0.0.1', 59724)

  File "C:\Users\34565\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 354, in finish_request

----------------------------------------

    self.RequestHandlerClass(request, client_address, self)

  File "C:\Users\34565\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 681, in __init__

    self.handle()

  File "C:/Users/34565/PycharmProjects/untitled/socket_server_tcp2.py", line 12, in handle

    data = conn.recv(1024)

OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。

# 服务端

import socketserver
import random
class MyServer(socketserver.BaseRequestHandler):
    def setup(self):
        pass
    def handle(self):

        conn = self.request
        msg = "hello"
        conn.send(msg.encode())
        while True:
            data = conn.recv(1024)
            print(data.decode())
            if data == b'exit':
                break
            conn.send(data)
            conn.send(str(random.randint(1,1000)).encode())
            conn.close()
    def finish(self):
        pass

if __name__ == "__main__":
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 8888), MyServer)
    server.serve_forever()

# 客户端

import socket
client = socket.socket()
ip_port = ("127.0.0.1", 8888)
client.connect(ip_port)
# 定义一个循环
while True:
    #不断接受消息
    data = client.recv(1024)
    print(data.decode())
    # 不断发送消息
    msg_input = input(":")
    client.send(msg_input.encode())
    if msg_input == "exit":
        break
    # 对消息处理
    data = client.recv(1024)
    print(data.decode())

请问是怎么回事?

写回答 关注

1回答

  • 知了海龙
    2019-05-29 00:27:55

    服务端的conn.close()要在while循环的外面,不然你已经关闭了,就会重新连接



    qq_慕桂英...

    谢谢大佬!终于解决了

    2020-05-27 12:49:10

    共 1 条回复 >

python运维-Socket网络编程

Socket网络编程入门

22579 学习 · 71 问题

查看课程

相似问题