Subscribing over TCP, deserializing each recieved JSON line

早过忘川 提交于 2019-12-11 19:13:07

问题


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

Well, this is a pseudocode I got, and I have no idea how to rewrite it in C#. I got something like this:

TcpClient connection = new TcpClientWithTimeout(host, 20059, 20000).Connect();
NetworkStream stream = connection.GetStream();

I have no idea how to replace the "tcp_connection.on", so, after I've subscribed over TCP, each line I get gets converted to string using json.decode(in case it helps, response format is:

{"result":"success/error","source": "{source}","success":{"time": TIME RECEIVED,"line":"RECEIVED LINE"}} )

回答1:


Something like:

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}");

After that you just start reading lines:

while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine("Got event: " + line);
}


来源:https://stackoverflow.com/questions/14959653/subscribing-over-tcp-deserializing-each-recieved-json-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!