C# 通过TCP订阅,反序列化每个接收到的JSON行
嗯,这是我得到的伪代码,我不知道如何用C#重写它。我得到了这样的东西:C# 通过TCP订阅,反序列化每个接收到的JSON行,c#,json,streaming,deserialization,tcpclient,C#,Json,Streaming,Deserialization,Tcpclient,嗯,这是我得到的伪代码,我不知道如何用C#重写它。我得到了这样的东西: tcp_connection = tcp_connect('localhost', 20060) // the server will always send responses on one line. tcp_connection.on('line', function (line) { json = json.decode(line) if(json.result == "success") { // etc,
tcp_connection = tcp_connect('localhost', 20060)
// the server will always send responses on one line.
tcp_connection.on('line', function (line) {
json = json.decode(line)
if(json.result == "success") {
// etc, etc, etc.
}
})
tcp_connection.write("/api/subscribe?source={sourceName}&key={key}&show_previous={true|false}") //stream API request
我不知道如何替换“tcp_connection.on”,因此,在我通过tcp订阅之后,我得到的每一行都会使用json.decode转换为字符串(如果有帮助,响应格式为:
TcpClient connection = new TcpClientWithTimeout(host, 20059, 20000).Connect();
NetworkStream stream = connection.GetStream();
比如:
{"result":"success/error","source": "{source}","success":{"time": TIME RECEIVED,"line":"RECEIVED LINE"}} )
之后,您只需开始阅读以下内容:
TcpClient connection = new TcpClientWithTimeout(host, 20059, 20000).Connect();
NetworkStream stream = connection.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
var line = reader.ReadLine();
if (line != "success")
throw new InvalidOperationException("Failed to connect");
writer.WriteLine(@"/api/subscribe?source={sourceName}&key={key}&show_previous={true|false}");
谢谢你,几乎可以了。我将发布一个关于我的新问题的新问题。
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("Got event: " + line);
}