【问题标题】:I am getting a weird error with an OSError ID: WinError 10038我收到一个带有 OSError ID 的奇怪错误:WinError 10038
【发布时间】:2017-01-18 23:25:49
【问题描述】:

我正在尝试使用以下代码编写服务器。它是线程化的,我需要帮助的只是这个错误。

Unhandled exception in thread started by <function threaded_client at 0x0000000003302158>
line 28, in threaded_client
data = conn.recv(2048)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

这个错误我无法解决并且已经尝试解决。我真的很想知道如何解决它。

import socket
import sys

from _thread import *
import time

host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((host,port))
except socket.error as e:
    print(str(e))    


s.listen(5)

print("Waiting for a Connection...")
def threaded_client(conn):

    conn.send(str.encode("Welcome, please write to the server.\r\n"))
    userinput = ""

    while True:
        data = conn.recv(2048)
        data = data.decode('utf-8')
        if not data:
            break
        #data = data.decode('utf-8')
        #Gather up the Input
        if data == '\r\n':
            userinput += data
        #Do something with it
        else:
            reply = 'Server output: ' + userinput
            conn.sendall(str.encode(reply))
            userinput = ""

            conn.close()
while True:
    conn, addr = s.accept()
    print("connected to: " +addr[0] + ': ' + str(addr[1]))
    start_new_thread(threaded_client, (conn,))    

现在我遇到了服务器与客户端交互方式的问题。我的 CMD 窗口的图像在下面打开。请提供修复代码。 对于 Windows 8,请。

【问题讨论】:

标签: python python-3.x runtime-error


【解决方案1】:

检查这部分。

else:
     reply = 'Server output: ' + userinput
     conn.sendall(str.encode(reply))
     userinput = ""
     conn.close() #<--- here you are closing the connection

这应该在循环之外。像这样。

while True:
        data = conn.recv(2048)
        data = data.decode('utf-8')
        if not data:
            break
        #data = data.decode('utf-8')
        #Gather up the Input
        if data == '\r\n':
            userinput += data
        #Do something with it
        else:
            reply = 'Server output: ' + userinput
            conn.sendall(str.encode(reply))
            userinput = ""

conn.close() #<--- Notice the indent

【讨论】:

  • 感谢 Prajwal - 很快就会测试
  • 很抱歉再次打扰您-但我有一个问题,每次击键后它都会打印出“服务器输出”消息,并且我希望在用户按下回车键后得到它。你知道怎么做吗?
  • 很抱歉打扰您 - 但我需要您帮助解决问题的另一部分。stackoverflow.com/questions/41739306/…>
猜你喜欢
  • 2011-11-09
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2023-03-11
  • 2019-12-21
  • 2021-09-22
  • 1970-01-01
  • 2015-02-06
相关资源
最近更新 更多