问题描述
我已经在这里继续这个问题,因为重点已经改变,但是是相关的.
I've continued this question here, because the focus has changed, but is related.
Vapor 正在服务器和 iOS 客户端之间进行通信.只是设置代码,用于学习目的.
Vapor is communicating between a server and and iOS client. Just setup code, for learning purposes.
现在,我想使用 JSON 通过已建立的连接发送值字典.我陷入了无法解释的演示代码逻辑中,但在我的蒸气路线中,这就是我所处的位置:
Now, I want to send a dictionary of values via the established connection using JSON. I'm getting caught up in the unexplained logic of demo code, but here's where I am, in my vapor routes:
app.webSocket("respond") { req, ws in
ws.onText { ws, text in
print(text)
let msgDict = "{'name' = 'bobby'}"
let encoder = JSONEncoder()
let data = try encoder.encode(msgDict)
ws.send(data)
}
}
这将无法编译: Invalid conversion from throwing function of type '(WebSocket, String) throws ->()' 到非抛出函数类型 '(WebSocket, String) ->()'
虽然我通常理解这个错误,并且取决于我如何玩这个错误.
while I generally understand this error, and dependent on how I play with this it varies.
通常我要寻找的是一个简单的模式来获取内部字典值,将它们编码为 JSON,然后发送它们.什么是我没有做的,或者我做的不对?
What generally I'm looking for is a simple pattern to take internal dictionary values, encode them into JSON, and send them. What am I not doing, or not doing right?
推荐答案
我发现该代码存在两个问题.
I see two problems with that code.
第一个,由编译错误解释,它实际上告诉它不会处理抛出的任何错误.当您执行 encoder.encode(msgDict)
时,此代码可能会抛出 Error
,并且您不会在任何地方处理此可能的错误.如果您处理了那个可能的错误,您在该闭包中编写的代码将具有预期的类型.您有几种选择:
The first one, explained by the compiling error, it's actually telling that it will not handle any errors thrown. When you do encoder.encode(msgDict)
, this code can throw an Error
, and you're not handling this possible error anywhere. If you handle that possible error, code you wrote in that closure will have the expected type. You have a few options to do so:
- 将代码包裹在
do-catch
块中
do {
let data = try encoder.encode(msgDict)
ws.send(data)
} catch let error {
// Handle error
}
- 使用
try?
,意味着如果发生错误,您不处理错误而是得到nil
. - Use
try?
, means you do not handle the error but getnil
as a result, if an error occurred.
if let data = try? encoder.encode(msgDict) {
ws.send(data)
}
- 使用
try!
,意味着您强制解包结果(不建议,但您可以尝试,如果您 100% 确定) - Use
try!
, means you force-unwrap the result (not advisable, but you can try, if you're 100% sure)
let data = try! encoder.encode(msgDict)
ws.send(data)
第二个问题是您如何编写该响应 - "{'name' = 'bobby'}"
.这是一个无效的 JSON,您应该使用双引号:
The second problem is how you're writing that response - "{'name' = 'bobby'}"
. This is an invalid JSON, you should use double quotes instead:
let msgDict = "{\"name\" = \"bobby\"}"
你也可以使用Dictionary
,只要内容是Encodable
类型:
You can also use Dictionary
, as long as the content is of type Encodable
:
let msgDict = ["name": "bobby"]
您还可以使用 JSONEncoder
对符合 Encodable
的类的任何实例进行编码.
You can also use JSONEncoder
to encode any instances of classes that conform to Encodable
.
所以整件事,我会这样写:
So the whole thing, I'd write like this:
app.webSocket("respond") { req, ws in
ws.onText { ws, text in
print(text)
let msgDict = ["name": "bobby"]
let encoder = JSONEncoder()
do {
let data = try encoder.encode(msgDict)
ws.send(data)
}
catch let error {
print("An error occurred: \(error)")
}
}
}
这篇关于如何使用 Vapor Websockets 向客户端发送字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!