2013-02-19 58 views
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#中重寫它。我有這樣的事情:通過TCP訂閱,反序列化每個接收的JSON行

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

回答

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); 
} 
+0

謝謝,差不多工作。我會發佈一個關於我的新問題的新問題。 – niklon 2013-02-24 14:39:41