问题
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