【问题标题】:Python server - error on launchPython 服务器 - 启动时出错
【发布时间】:2015-09-28 17:08:33
【问题描述】:

我已经使用 python 创建了一个服务器: 这是脚本:

import socket,threading

class ClientThread(threading.Thread): 
    def __init__(self, ip, port, clsock):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.clsock = clsock
    def run(self): 
        print ("Connection from : "+self.ip+":"+str(self.port))

        #----
        self.clsock.send("Welcome to the server")
        data = self.clsock.recv(2048)
        while 1:
            self.clsock.send(data+" "+data)
            data = self.clsock.recv(2048)
        #----

        print "Client disconnected..."

listathread = []
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.0.14", 2837))
server_socket.listen(5)
while 1:
    server_socket.listen(5)
    print ("listening for connections...")
    (clientsock, (ip2, port2)) = server_socket.accept()
    newthread = ClientThread(ip2, port2, clientsock)
    newthread.run()
    listathread.append(newthread)

问题是,当我使用 Python Shell 启动此脚本时,它运行良好,但是当我将其保存为 .py 文件并使用经典双击启动它时,程序给了我错误并在一秒钟内关闭!

我真的不明白发生了什么! 您有解决此问题的想法吗?

【问题讨论】:

  • 打开命令行输入python .py 出现什么错误?

标签: python server


【解决方案1】:

我找到了解决问题的方法:我必须在脚本的第一行编写以下代码:

# -*- coding: cp1252 -*-

所以现在我有:

# -*- coding: cp1252 -*-
import socket,threading

class ClientThread(threading.Thread):
    def __init__(self, ip, port, clsock):
        threading.Thread.__init__(self)

...code...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多