我是网络套接字的新手,但现在太清楚它是如何工作的。我的问题就在下面:我想区分两个事件的结果。
interface IWebSocketMethod
{
void GetTicker();
void GetOrderBook();
void GetTrades();
}
abstract class WebSocket
{
private WebSocket4Net.WebSocket Socket;
public WebSocket(string webSocketUrl)
{
Socket = new WebSocket4Net.WebSocket(webSocketUrl);
Socket.Opened += new EventHandler(OpenEventHandler);
Socket.Error += new EventHandler<ErrorEventArgs>(ErrorEventHandler);
Socket.Closed += new EventHandler(CloseEventHandler);
Socket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(MessageReceivedEventHandler);
Socket.Open();
Thread.Sleep(5000);
}
public virtual void OpenEventHandler(object sender, EventArgs e)
{
Console.WriteLine("Connection Open");
}
public virtual void ErrorEventHandler(object sender, ErrorEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
public virtual void CloseEventHandler(object sender, EventArgs e)
{
Console.WriteLine("Connection close");
}
public virtual void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
public virtual void Request(string data)
{
Socket.Send(data);
}
}
class BitFinexWebSocket : WebSocket, IWebSocketMethod
{
public BitFinexWebSocket():base("wss://api.bitfinex.com/ws")
{
GetTicker();
//GetOrderBook();
GetTrades();
}
public void GetTicker()
{
var obj = new { @event = "subscribe", channel = "ticker", pair = "BTCUSD" };
var body = JsonConvert.SerializeObject(obj).ToLower();
Request(body);
}
public void GetOrderBook()
{
var obj = new { @event = "subscribe", channel = "book", pair = "BTCUSD" };
var body = JsonConvert.SerializeObject(obj).ToLower();
Request(body);
}
public void GetTrades()
{
var obj = new { @event = "subscribe", channel = "trades", pair = "BTCUSD" };
var body = JsonConvert.SerializeObject(obj).ToLower();
Request(body);
}
public override void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message.ToString());
}
}
现在在这段代码中我订阅了两个事件,但在MessageReceivedEventHandler中我如何区分结果。或者我必须创建多个Web套接字连接。在此先感谢
答案 0 :(得分:0)
我创建了一个具有channel属性的基类模型,首先对它进行反序列化以确定该信道。然后,一旦确定了哪个信道,便可以使用该信道的适当响应模型再次对其进行反序列化。
public enum Channel
{
[EnumMember(Value = "ticker")]
TICKER,
[EnumMember(Value = "book")]
BOOK,
[EnumMember(Value = "trade")]
TRADES
}
public class Response
{
[JsonProperty("channel")]
[JsonConverter(typeof(StringEnumConverter))]
public Channel Channel { get; set; }
}
public class TradeResponse : Response
{
public string Symbol;
public DateTime time;
...
}
public override void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs e)
{
Response res = JsonConvert.DeserializeObject<Response>(e.Message.ToString());
switch (res.Channel)
{
case Channel.TRADES:
TradeResponse trade = JsonConvert.DeserializeObject<TradeResponse>(e.Message.ToString());
// ...
break;
case Channel.BOOK:
break;
case Channel.TICKER:
break;
default:
throw new System.Exception("Unsupported channel");
}
Console.WriteLine(e.Message.ToString());
}