0
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

嗯,这是我得到的一个伪代码,我不知道如何用 C# 重写它。我得到了这样的东西:

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

我不知道如何替换“tcp_connection.on”,所以,在我通过 TCP 订阅后,我得到的每一行都使用 json.decode 转换为字符串(如果有帮助,响应格式为:

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

1 回答 1

0

就像是:

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);
}
于 2013-02-21T07:12:22.873 回答