【问题标题】:Creating Twisted TCP socket and sending test value创建 Twisted TCP 套接字并发送测试值
【发布时间】:2012-05-11 08:44:44
【问题描述】:

我正在使用 TCP/IP 协议设置套接字,并且由于我的接收器正在处理 int8u_t,我想知道这种方法是否正确。

在连接时,服务器必须向接收者发送一个值mode=int(42),这在def connectionMade(self) 中完成。但我知道会有一些冲突,因为 python 中的普通 int 是 32 位的,而我的接收器只有 8 位,我可以以某种方式转换它或在 int8u 中创建它吗?

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class TestSocket(Protocol):
        def connectionMade(self):
                mode=int(42)
                self.factory.clients.append(self)
                self.transport.write(mode)
                print "clients are ", self.factory.clients

        def connectionLost(self, reason):
            self.factory.clients.remove(self)

        def dataReceived(self, data):
                #print "data is ", data
                #a = data.split(':')
                print data
                print "-------------------"

        def message(self, message):
                self.transport.write(message + '\n')

factory = Factory()
factory.protocol = TestSocket()
factory.clients = []

reactor.listenTCP(30002, factory)
print "TestSocket server started"
reactor.run()

【问题讨论】:

  • mode=int(42) 可以更好地表达为mode = 42

标签: python twisted twisted.internet


【解决方案1】:

您可以使用numpy

import numpy
mode = numpy.int8(42)  # int8   Byte (-128 to 127)

您可以找到有关类型和类型之间转换的更多信息 使用numpyhere

【讨论】:

    【解决方案2】:

    使用结构

    from struct import *
    mode = pack("h", 42) # 'h' == short
    

    编辑:显然你想要pack("I", 42)

    【讨论】:

      猜你喜欢
      • 2012-07-31
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多