【问题标题】:python while true wierd error [closed]python while true wierd error [关闭]
【发布时间】:2018-09-10 12:57:00
【问题描述】:

我目前正在学习 python 一个月,因为我想为我的 GameMakerStudio 2 游戏编​​写一个服务器,它不支持线程,我需要一个用另一种语言编写的服务器才能使其可用。 无论如何... https://www.youtube.com/watch?v=WrtebUkUssc -教程网址

我正在关注本教程,不幸的是我收到了一个错误:

/home/borut/PycharmProjects/Server/venv/bin/python /home/borut/PycharmProjects/Server/Server.py 文件“/home/borut/PycharmProjects/Server/Server.py”,第 19 行 而真: ^ IndentationError: 意外缩进

进程以退出代码 1 结束

我在教程中的代码是:

import socket
import sys
from _thread import *

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, type your info\n'))

        while True:
                data = conn.recv(2048)
                reply = 'Server output: ' +data.decode('utf-8')
                if not data:
                    break;
                 conn.sendall(str.encode(reply))
                conn.close()

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

                start_new_thread(threaded_client, (conn,))

感谢您的所有回答和提示!

【问题讨论】:

标签: python networking


【解决方案1】:

问题是您的缩进不正确。我的意思是缩进

逻辑开头的前导空格(空格和制表符) line 用于计算行的缩进级别,其中 turn用于确定语句的分组

This link 有助于您了解为什么缩进很重要。

要解决此问题,请使用 IDE 格式化代码。您可以改用此代码,我已为您修复了缩进。

import socket
import sys
from _thread import *

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, type your info\n'))

    while True:
        data = conn.recv(2048)
        reply = 'Server output: ' +data.decode('utf-8')
        if not data:
             break
        conn.sendall(str.encode(reply))
        conn.close()

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

        start_new_thread(threaded_client, (conn,))

【讨论】:

    【解决方案2】:

    缩进是 Python 最重要的思想,因为它是您告知代码块开始/结束位置的方式。

    你的第一个

    while True:
    

    前面是一个制表符

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2015-06-21
      相关资源
      最近更新 更多