Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不发送数据_Python_Twisted - Fatal编程技术网

Python 不发送数据

Python 不发送数据,python,twisted,Python,Twisted,server.py from twisted.python import log from twisted.internet import reactor,ssl, protocol import config import uuid import json import header class cl: clients = list() source = None sourceID = None sent_header = list() id3_hea

server.py

from twisted.python import log
from twisted.internet import reactor,ssl, protocol
import config
import uuid
import json
import header

class cl:
    clients = list()
    source = None
    sourceID = None
    sent_header = list()
    id3_headers = {
        "pyc-title": "None",
        "pyc-length": "0",
    }

class RadioServer(protocol.Protocol):

    def connectionMade(self):
        if config.PyCasterMaxListeners != len(cl.clients):
            self.id = str(uuid.uuid4())
            self.peer = str(self.transport.getPeer())
            self.transport.write(header.header)
            cl.clients.append(self)
            print("Client-Connected-IP: "+self.peer)
            print("Client-Connected-ID: " + self.id)
        else:
            self.transport.abortConnection()

    def connectionLost(self, reason):
        if self.id == cl.sourceID:
            print("Source-Closed: "+ str(reason))
            cl.sourceID = None
            cl.source = None
        else:
            self.removeClient(self.id)
            print("Client-Closed-Reason: " + reason)
            print("Client-Closed-IP: " + self.peer)
            print("Client-Closed-ID: " + self.id)

    def dataReceived(self, data):
        dct = json.loads(data, encoding="utf8")
        if dct.has_key("PyCasterAuth"):
            if not cl.sourceID:
                auth = dct['PyCasterAuth']
                if auth == config.PyCasterAuth:
                    cl.source = self
                    cl.sourceID = self.id
                    self.transport.write("ok")
                    print("Source-Registered")
                    print("Source-ID: " + self.id)
                else:
                    cl.source.transport.write("denied")
                    print("Source-Login-Denied-IP: " + self.peer)
                    print("Source-Login-Denied-ID: " + self.id)
            else:
                print("Source-Exists-IP: " + self.peer)
                print("Source-Exists-ID: " + self.id)
                self.closeCl(self.id)
        elif dct.has_key("buffer"):
            buffer = dct['buffer']
            self.sendClients(buffer, bin=True)

        elif dct.has_key("info"):
            cl.id3_headers = dct['info']

    def removeClient(self, id):
        for client in cl.clients:
            if client.id == id:
                cl.clients.remove(cl)
                if client in cl.sent_header:
                    cl.sent_header.remove(client)

    def closeCl(self, id):
        for client in cl.clients:
            if client.id == id:
                self.removeClient(id)
                client.transport.abortConnection()
                print("Server-Closed-Client: (%s, %s)" % (id, client.peer))

    def sendClients(self, msg, bin=False):
        for client in cl.clients:
            if bin:
                if client not in cl.sent_header:
                    head = header.header
                    for k, v in iter(cl.id3_headers.items()):
                        head += k + ":" + v
                    client.transport.write("HTTP/1.1 200 OK\r\n")
                    client.transport.write(head)
            client.transport.write(msg)
            if config.PyCasterSendLogging:
                print("SENT %i bytes TO %s" % (len(msg), client.id))


if __name__=="__main__":
    import sys
    key = config.PyCasterSSLKey
    cert = config.PyCasterSSLCert
    factory = protocol.Factory()
    log.startLogging(sys.stdout)
    factory.protocol = RadioServer
    if config.PyCasterSSL:
        reactor.listenSSL(config.PyCasterPort, factory,  ssl.DefaultOpenSSLContextFactory(key, cert))
        reactor.run()
    else:
        reactor.listenTCP(config.PyCasterPort, factory)
        reactor.run()
PyCasterAuth = "123abc"
PyCasterPort = 4446
PyCasterSSL = False
PyCasterSSLKey = None
PyCasterSSLCert = None
PyCasterMaxListeners = 32
PyCasterSendLogging = True
PyCasterLogFile=open("pycaster.log", "w") #can be sys.stdout
config.py

from twisted.python import log
from twisted.internet import reactor,ssl, protocol
import config
import uuid
import json
import header

class cl:
    clients = list()
    source = None
    sourceID = None
    sent_header = list()
    id3_headers = {
        "pyc-title": "None",
        "pyc-length": "0",
    }

class RadioServer(protocol.Protocol):

    def connectionMade(self):
        if config.PyCasterMaxListeners != len(cl.clients):
            self.id = str(uuid.uuid4())
            self.peer = str(self.transport.getPeer())
            self.transport.write(header.header)
            cl.clients.append(self)
            print("Client-Connected-IP: "+self.peer)
            print("Client-Connected-ID: " + self.id)
        else:
            self.transport.abortConnection()

    def connectionLost(self, reason):
        if self.id == cl.sourceID:
            print("Source-Closed: "+ str(reason))
            cl.sourceID = None
            cl.source = None
        else:
            self.removeClient(self.id)
            print("Client-Closed-Reason: " + reason)
            print("Client-Closed-IP: " + self.peer)
            print("Client-Closed-ID: " + self.id)

    def dataReceived(self, data):
        dct = json.loads(data, encoding="utf8")
        if dct.has_key("PyCasterAuth"):
            if not cl.sourceID:
                auth = dct['PyCasterAuth']
                if auth == config.PyCasterAuth:
                    cl.source = self
                    cl.sourceID = self.id
                    self.transport.write("ok")
                    print("Source-Registered")
                    print("Source-ID: " + self.id)
                else:
                    cl.source.transport.write("denied")
                    print("Source-Login-Denied-IP: " + self.peer)
                    print("Source-Login-Denied-ID: " + self.id)
            else:
                print("Source-Exists-IP: " + self.peer)
                print("Source-Exists-ID: " + self.id)
                self.closeCl(self.id)
        elif dct.has_key("buffer"):
            buffer = dct['buffer']
            self.sendClients(buffer, bin=True)

        elif dct.has_key("info"):
            cl.id3_headers = dct['info']

    def removeClient(self, id):
        for client in cl.clients:
            if client.id == id:
                cl.clients.remove(cl)
                if client in cl.sent_header:
                    cl.sent_header.remove(client)

    def closeCl(self, id):
        for client in cl.clients:
            if client.id == id:
                self.removeClient(id)
                client.transport.abortConnection()
                print("Server-Closed-Client: (%s, %s)" % (id, client.peer))

    def sendClients(self, msg, bin=False):
        for client in cl.clients:
            if bin:
                if client not in cl.sent_header:
                    head = header.header
                    for k, v in iter(cl.id3_headers.items()):
                        head += k + ":" + v
                    client.transport.write("HTTP/1.1 200 OK\r\n")
                    client.transport.write(head)
            client.transport.write(msg)
            if config.PyCasterSendLogging:
                print("SENT %i bytes TO %s" % (len(msg), client.id))


if __name__=="__main__":
    import sys
    key = config.PyCasterSSLKey
    cert = config.PyCasterSSLCert
    factory = protocol.Factory()
    log.startLogging(sys.stdout)
    factory.protocol = RadioServer
    if config.PyCasterSSL:
        reactor.listenSSL(config.PyCasterPort, factory,  ssl.DefaultOpenSSLContextFactory(key, cert))
        reactor.run()
    else:
        reactor.listenTCP(config.PyCasterPort, factory)
        reactor.run()
PyCasterAuth = "123abc"
PyCasterPort = 4446
PyCasterSSL = False
PyCasterSSLKey = None
PyCasterSSLCert = None
PyCasterMaxListeners = 32
PyCasterSendLogging = True
PyCasterLogFile=open("pycaster.log", "w") #can be sys.stdout
header.py
包含要发送的头数据变量


我提供了整个服务器,因此您可以运行并了解我的问题。如果正确,则在发送身份验证后,服务器发送
ok
,但问题是
self.transport.write(“ok”)
未被客户端看到。我尝试过谷歌搜索,但没有找到解决办法。

你的方法有很多问题。首先,您要继承echo服务器的方法,并走出困境。从外观上看,您似乎需要一个HTTP服务器。请看下面的请求和响应示例

如果您需要了解代码中的问题,也可以这样做。那么主要是你收到的数据

def dataReceived(self, data):
    dct = json.loads(data, encoding="utf8")
    if dct.has_key("PyCasterAuth"):
        if not cl.sourceID:
            auth = dct['PyCasterAuth']
            if auth == config.PyCasterAuth:
                cl.source = self
                cl.sourceID = self.id
                self.transport.write("ok")
                print("Source-Registered")
                print("Source-ID: " + self.id)
            else:
                cl.source.transport.write("denied")
                print("Source-Login-Denied-IP: " + self.peer)
                print("Source-Login-Denied-ID: " + self.id)
        else:
            print("Source-Exists-IP: " + self.peer)
            print("Source-Exists-ID: " + self.id)
            self.closeCl(self.id)
    elif dct.has_key("buffer"):
        buffer = dct['buffer']
        self.sendClients(buffer, bin=True)

    elif dct.has_key("info"):
        cl.id3_headers = dct['info']
您假设
数据
将具有主体。虽然这不是真的,但它也会有标题。所以你的电话会失败。下面是一个可以添加的简单解决方法

    data_body = data.split(b"\r\n\r\n")[1]
    dct = json.loads(data_body, encoding="utf8")
下一个密钥检查应该这样做

    if "PyCasterAuth" in dct:
因为没有方法
具有_键
。另外,在接收到的数据结束时,您希望关闭请求,这样它就不会继续等待

self.transport.loseConnection()
因此,更新后的函数如下所示

def dataReceived(self, data):
    data_body = data.split(b"\r\n\r\n")[1]
    dct = json.loads(data_body, encoding="utf8")
    if "PyCasterAuth" in dct:
        if not cl.sourceID:
            auth = dct['PyCasterAuth']
            if auth == config.PyCasterAuth:
                cl.source = self
                cl.sourceID = self.id
                self.transport.write(b"ok")
                print("Source-Registered")
                print("Source-ID: " + self.id)
            else:
                cl.source.transport.write("denied")
                print("Source-Login-Denied-IP: " + self.peer)
                print("Source-Login-Denied-ID: " + self.id)
        else:
            print("Source-Exists-IP: " + self.peer)
            print("Source-Exists-ID: " + self.id)
            self.closeCl(self.id)
    elif dct.has_key("buffer"):
        buffer = dct['buffer']
        self.sendClients(buffer, bin=True)

    elif dct.has_key("info"):
        cl.id3_headers = dct['info']

    self.transport.loseConnection()
但正如我提到的,你不应该使用这种方法,而应该使用我添加的链接中的方法

下面是一个简单的测试

 curl -v -H "Content-Type: application/json" -X POST -d '{"PyCasterAuth":"123abc"}' localhost:4446
Note: Unnecessary use of -X or --request, POST is already inferred.
* Rebuilt URL to: localhost:4446/
*   Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 4446 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 4446 (#0)
> POST / HTTP/1.1
> Host: localhost:4446
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 25
>
* upload completely sent off: 25 out of 25 bytes
Name: Tarun
* Connection #0 to host localhost left intact
ok%

因此,您的方法存在多个问题。首先,您要继承echo服务器的方法,并走出困境。从外观上看,您似乎需要一个HTTP服务器。请看下面的请求和响应示例

如果您需要了解代码中的问题,也可以这样做。那么主要是你收到的数据

def dataReceived(self, data):
    dct = json.loads(data, encoding="utf8")
    if dct.has_key("PyCasterAuth"):
        if not cl.sourceID:
            auth = dct['PyCasterAuth']
            if auth == config.PyCasterAuth:
                cl.source = self
                cl.sourceID = self.id
                self.transport.write("ok")
                print("Source-Registered")
                print("Source-ID: " + self.id)
            else:
                cl.source.transport.write("denied")
                print("Source-Login-Denied-IP: " + self.peer)
                print("Source-Login-Denied-ID: " + self.id)
        else:
            print("Source-Exists-IP: " + self.peer)
            print("Source-Exists-ID: " + self.id)
            self.closeCl(self.id)
    elif dct.has_key("buffer"):
        buffer = dct['buffer']
        self.sendClients(buffer, bin=True)

    elif dct.has_key("info"):
        cl.id3_headers = dct['info']
您假设
数据
将具有主体。虽然这不是真的,但它也会有标题。所以你的电话会失败。下面是一个可以添加的简单解决方法

    data_body = data.split(b"\r\n\r\n")[1]
    dct = json.loads(data_body, encoding="utf8")
下一个密钥检查应该这样做

    if "PyCasterAuth" in dct:
因为没有方法
具有_键
。另外,在接收到的数据结束时,您希望关闭请求,这样它就不会继续等待

self.transport.loseConnection()
因此,更新后的函数如下所示

def dataReceived(self, data):
    data_body = data.split(b"\r\n\r\n")[1]
    dct = json.loads(data_body, encoding="utf8")
    if "PyCasterAuth" in dct:
        if not cl.sourceID:
            auth = dct['PyCasterAuth']
            if auth == config.PyCasterAuth:
                cl.source = self
                cl.sourceID = self.id
                self.transport.write(b"ok")
                print("Source-Registered")
                print("Source-ID: " + self.id)
            else:
                cl.source.transport.write("denied")
                print("Source-Login-Denied-IP: " + self.peer)
                print("Source-Login-Denied-ID: " + self.id)
        else:
            print("Source-Exists-IP: " + self.peer)
            print("Source-Exists-ID: " + self.id)
            self.closeCl(self.id)
    elif dct.has_key("buffer"):
        buffer = dct['buffer']
        self.sendClients(buffer, bin=True)

    elif dct.has_key("info"):
        cl.id3_headers = dct['info']

    self.transport.loseConnection()
但正如我提到的,你不应该使用这种方法,而应该使用我添加的链接中的方法

下面是一个简单的测试

 curl -v -H "Content-Type: application/json" -X POST -d '{"PyCasterAuth":"123abc"}' localhost:4446
Note: Unnecessary use of -X or --request, POST is already inferred.
* Rebuilt URL to: localhost:4446/
*   Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 4446 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 4446 (#0)
> POST / HTTP/1.1
> Host: localhost:4446
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 25
>
* upload completely sent off: 25 out of 25 bytes
Name: Tarun
* Connection #0 to host localhost left intact
ok%