gpt4 book ai didi

python - Swift NSSocket 编程/python 教程修复

转载 作者:搜寻专家 更新时间:2023-11-01 05:37:02 24 4
gpt4 key购买 nike

我对 Python 几乎一无所知,但我正在尝试快速学习 NSSockets 教程;并且使用python。这是 python 脚本。脚本在 python2 中,但我必须在 python 3 下运行它。

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

class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print("clients are ", self.factory.clients)

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

def dataReceived(self, data):
a = data.split(':')
print(a)
if len(a) > 1:
command = a[0]
content = a[1]

msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"

elif command == "msg":
msg = self.name + ": " + content
print(msg)

for c in self.factory.clients:
c.message(msg)

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


factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print("Iphone Chat server started")
reactor.run()

它可以工作,但是当我尝试连接我的 Swift 代码时,它会因这条消息而崩溃。

File "server.py", line 13, in dataReceived
a = data.split(':')
builtins.TypeError: a bytes-like object is required, not 'str'

提示我发送的数据格式不对;这是发送消息的 swift 代码。

func sayhello() {
let response = String(format:"iam:brian")
let dataToSend = [UInt8](response.utf8)
outputStream?.write(dataToSend, maxLength: dataToSend.count)
}

如何修复 swift 或 python?我尝试遵循/翻译的教程在里面。

https://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server

最佳答案

感谢https://stackoverflow.com/users/1076479/gil-hamilton链接 我设法弄清楚我在看什么。解决方案。我使用的是与此处发布的相同的 swift 代码,我删除了 python 的最后一部分。我正在发送和接收这个。

Iphone Chat server started
clients are [<__main__.IphoneChat object at 0x1035039e8>]
b'iam:brian'

现在我知道问题出在哪里了,用python我可以找到答案!我基本上在 python 脚本中删除了它。

def dataReceived(self, data):
a = data.split(':')
print(a)
if len(a) > 1:
command = a[0]
content = a[1]

msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"

elif command == "msg":
msg = self.name + ": " + content
print(msg)

for c in self.factory.clients:
c.message(msg)

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

并用这个替换它......

def dataReceived(self, data):
print(data)
dumb=data.decode('utf8')
print(dumb)

它是如此简单,它是愚蠢的....

关于python - Swift NSSocket 编程/python 教程修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com