internal void ClientDisconnected(IAsyncResult asyncResult) { SocketConnectionInfo _connection = (SocketConnectionInfo)asyncResult.AsyncState; OnClientDisconnected.RaiseEvent(null, CreateSocketSeesion(_connection, null)); _connection.Socket.EndDisconnect(asyncResult); }
/// <summary> /// 处理数据异步接收 /// </summary> /// <param name="asyncResult">IAsyncResult</param> /// 时间:2016/6/7 22:56 /// 备注: internal void DataReceived(IAsyncResult asyncResult) { try { SocketConnectionInfo _connection = (SocketConnectionInfo)asyncResult.AsyncState; int _bytesRead = CaluDataReceivedReadLength(_connection, asyncResult); _connection.BytesRead += _bytesRead; if (IsSocketConnected(_connection.Socket)) { HanlderIsSocketConnectedDataReceived(_connection, _bytesRead, asyncResult); } else if (_connection.BytesRead > 0) { HanlderSpecialDataReceived(_connection, _bytesRead, asyncResult); } else { HanlderTcpClientDisconnected(_connection, _bytesRead, asyncResult); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void OnKlineSocketError(object sender, ErrorEventArgs e) { SocketConnectionInfo info = KlineSockets[(WebSocket)sender]; info.State = SocketConnectionState.Error; info.LastError = e.Exception.ToString(); }
protected override void OnOrderBookSocketMessageReceived(object sender, MessageReceivedEventArgs e) { base.OnOrderBookSocketMessageReceived(sender, e); LastWebSocketRecvTime = DateTime.Now; SocketConnectionInfo info = OrderBookSockets[(WebSocket)sender]; JObject obj = JsonConvert.DeserializeObject <JObject>(e.Message); JArray items = obj.Value <JArray>("data"); if (items == null) { return; } OrderBookUpdateType type = String2UpdateType(obj.Value <string>("action")); foreach (JObject item in items) { Ticker t = info.Ticker; OrderBookEntryType entryType = item.Value <string>("side")[0] == 'S' ? OrderBookEntryType.Ask : OrderBookEntryType.Bid; string rate = type == OrderBookUpdateType.Add ? item.Value <string>("price") : null; string size = type != OrderBookUpdateType.Remove ? item.Value <string>("size") : null; t.OrderBook.ApplyIncrementalUpdate(entryType, type, item.Value <long>("id"), rate, size); } }
protected override void OnTradeHistorySocketOpened(object sender, EventArgs e) { SocketConnectionInfo info = TradeHistorySockets[(WebSocket)sender]; info.State = SocketConnectionState.Connected; info.Ticker.TradeHistory.Clear(); }
protected override void OnOrderBookSocketOpened(object sender, EventArgs e) { SocketConnectionInfo info = OrderBookSockets[(WebSocket)sender]; info.State = SocketConnectionState.Connected; info.Ticker.UpdateOrderBook(); }
protected override void OnTradeHistorySocketError(object sender, ErrorEventArgs e) { SocketConnectionInfo info = TradeHistorySockets[(WebSocket)sender]; info.State = SocketConnectionState.Error; info.LastError = e.Exception.ToString(); }
/// <summary> /// 处理终端异步连接 /// </summary> /// <param name="asyncResult">IAsyncResult</param> /// 时间:2016/6/7 22:54 /// 备注: internal void ClientConnected(IAsyncResult asyncResult) { Interlocked.Increment(ref currentConnections); SocketConnectionInfo _connection = new SocketConnectionInfo(); _connection.Buffer = new byte[SocketConnectionInfo.BufferSize]; Socket _asyncListener = (Socket)asyncResult.AsyncState; Socket _asyncClient = _asyncListener.EndAccept(asyncResult); _connection.Socket = _asyncClient; if (OnClientConnected != null) { OnClientConnected(this, null); } if (this.Type == TCPIPType.TCP) { _asyncClient.BeginReceive(_connection.Buffer, 0, _connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), _connection); } else if (this.Type == TCPIPType.UDP) { _asyncClient.BeginReceiveFrom(_connection.Buffer, 0, _connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), _connection); } listener.BeginAccept(new AsyncCallback(ClientConnected), listener); }
public virtual void StopListenTickerStream(Ticker ticker) { SubscribedTickers.Remove(ticker); SocketConnectionInfo info = GetConnectionInfo(ticker, OrderBookSockets); if (info != null) { info.Socket.Error -= OnOrderBookSocketError; info.Socket.Opened -= OnOrderBookSocketOpened; info.Socket.Closed -= OnOrderBookSocketClosed; info.Socket.MessageReceived -= OnOrderBookSocketMessageReceived; info.Close(); info.Dispose(); OrderBookSockets.Remove(info.Socket); } info = GetConnectionInfo(ticker, TradeHistorySockets); if (info != null) { info.Socket.Error -= OnTradeHistorySocketError; info.Socket.Opened -= OnTradeHistorySocketOpened; info.Socket.Closed -= OnTradeHistorySocketClosed; info.Socket.MessageReceived -= OnTradeHistorySocketMessageReceived; info.Close(); info.Dispose(); TradeHistorySockets.Remove(info.Socket); } }
/// <summary> /// 处理tcp 终端连接断开 /// </summary> private void HanlderTcpClientDisconnected(SocketConnectionInfo connection, int bytesRead, IAsyncResult asyncResult) { if (OnClientDisconnected != null) { DisconnectClient(connection); } }
public override void StartListenTickerStream(Ticker ticker) { base.StartListenTickerStream(ticker); SocketConnectionInfo info = CreateOrderBookWebSocket(ticker); OrderBookSockets.Add(info.Socket, info); }
/// <summary> /// 处理tcp client断开事件 /// </summary> /// <param name="connection">SocketConnectionInfo</param> internal void DisconnectClient(SocketConnectionInfo connection) { OnClientDisconnecting.RaiseEvent(null, CreateSocketSeesion(connection, null)); if (connection.Socket != null) { connection.Socket.BeginDisconnect(true, new AsyncCallback(ClientDisconnected), connection); } }
internal void DisconnectClient(SocketConnectionInfo connection) { if (OnClientDisconnecting != null) { OnClientDisconnecting(this, null); } connection.Socket.BeginDisconnect(true, new AsyncCallback(ClientDisconnected), connection); }
private void gvConnections_MasterRowGetChildList(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetChildListEventArgs e) { if (e.RowHandle < 0) { return; } SocketConnectionInfo info = (SocketConnectionInfo)this.gvConnections.GetRow(e.RowHandle); e.ChildList = info.Subscribtions; }
protected override void OnTradeHistorySocketMessageReceived(object sender, MessageReceivedEventArgs e) { byte[] bytes = Encoding.Default.GetBytes(e.Message); int startIndex = 0; string[] trades = JSonHelper.Default.DeserializeObject(bytes, ref startIndex, TradeItems); SocketConnectionInfo info = TradeHistorySockets[(WebSocket)sender]; OnTradeHistoryItemRecv(info.Ticker, trades); }
internal void ClientDisconnected(IAsyncResult asyncResult) { SocketConnectionInfo _sci = (SocketConnectionInfo)asyncResult; _sci.Socket.EndDisconnect(asyncResult); if (OnClientDisconnected != null) { OnClientDisconnected(this, null); } }
private static void DataReceived(IAsyncResult ar) { var connection = (SocketConnectionInfo)ar.AsyncState; try { var bytesRead = connection.Socket.EndReceive(ar); connection.BytesRead += bytesRead; if (!IsSocketConnected(connection.Socket)) { // client disconnected but we have some data in buffer to read if (connection.BytesRead > 0) { Process(connection.Buffer); } } if (bytesRead == 0 || (bytesRead > 0 && bytesRead < SocketConnectionInfo.BufferSize)) { var buffer = connection.Buffer; if (bytesRead < buffer.Length) { Array.Resize(ref buffer, bytesRead); } Process(buffer); connection = new SocketConnectionInfo { Socket = ((SocketConnectionInfo)ar.AsyncState).Socket }; connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, DataReceived, connection); } else { Array.Resize(ref connection.Buffer, connection.Buffer.Length + SocketConnectionInfo.BufferSize); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, DataReceived, connection); } } catch (Exception ex) { Console.WriteLine(ex.Message); if (IsSocketConnected(connection.Socket)) { connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, DataReceived, connection); } Connect(_roomId, _clientId); } }
protected bool CheckProcessError(SocketConnectionInfo info) { if (info.LastError.Contains("Too Many Requests")) { info.ReconnectAfter(30); return(true); } else if (info.LastError.Contains("Forbidden")) { return(true); } return(false); }
private void biShowErrors_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { SocketConnectionInfo info = (SocketConnectionInfo)this.gvConnections.GetRow(this.gvConnections.FocusedRowHandle); if (info == null) { return; } using (ConnectionErrorHistoryForm form = new ConnectionErrorHistoryForm()) { form.SocketInfo = info; form.ShowDialog(); } }
protected internal override void OnTradeHistorySocketError(object sender, ErrorEventArgs e) { SocketConnectionInfo info = TradeHistorySockets.FirstOrDefault(c => c.Key == sender); if (info != null) { if (CheckProcessError(info)) { return; } } base.OnTradeHistorySocketError(sender, e); }
protected internal override void OnOrderBookSocketError(object sender, ErrorEventArgs e) { SocketConnectionInfo info = OrderBookSockets.FirstOrDefault(c => c.Key == sender); if (info != null) { info.Ticker.OrderBook.IsDirty = true; if (CheckProcessError(info)) { return; } } base.OnOrderBookSocketError(sender, e); }
protected internal override void OnTradeHistorySocketMessageReceived(object sender, MessageReceivedEventArgs e) { byte[] bytes = Encoding.Default.GetBytes(e.Message); int startIndex = 0; string[] trades = JSonHelper.Default.DeserializeObject(bytes, ref startIndex, TradeItems); SocketConnectionInfo info = TradeHistorySockets.FirstOrDefault(c => c.Key == sender); if (info != null && info.Ticker.CaptureData) { info.Ticker.CaptureDataCore(CaptureStreamType.TradeHistory, CaptureMessageType.Incremental, e.Message); } OnTradeHistoryItemRecv(info.Ticker, trades); }
protected SocketConnectionInfo CreateTradesWebSocket(Ticker ticker) { SocketConnectionInfo info = new SocketConnectionInfo(); string adress = GetTradeSocketAddress(ticker); info.Ticker = ticker; info.Adress = adress; info.Socket = new WebSocket(adress, ""); info.Socket.Error += OnTradeHistorySocketError; info.Socket.Opened += OnTradeHistorySocketOpened; info.Socket.Closed += OnTradeHistorySocketClosed; info.Socket.MessageReceived += OnTradeHistorySocketMessageReceived; info.Open(); return(info); }
protected internal override void OnTradeHistorySocketMessageReceived(object sender, MessageReceivedEventArgs e) { LastWebSocketRecvTime = DateTime.Now; SocketConnectionInfo info = TradeHistorySockets.FirstOrDefault(c => c.Key == sender); if (info == null) { return; } Ticker t = info.Ticker; if (t.IsUpdatingTrades) { return; } if (t.CaptureData) { t.CaptureDataCore(CaptureStreamType.TradeHistory, CaptureMessageType.Incremental, e.Message); } JObject obj = JsonConvert.DeserializeObject <JObject>(e.Message); JArray items = obj.Value <JArray>("data"); if (items == null) { return; } foreach (JObject item in items) { TradeInfoItem ti = new TradeInfoItem(null, t); ti.TimeString = item.Value <string>("timestamp"); ti.Type = String2TradeType(item.Value <string>("side")); ti.AmountString = item.Value <string>("size"); ti.RateString = item.Value <string>("price"); t.AddTradeHistoryItem(ti); //.InsertTradeHistoryItem(ti); } if (t.HasTradeHistorySubscribers) { TradeHistoryChangedEventArgs ee = new TradeHistoryChangedEventArgs() { NewItem = t.TradeHistory.First() }; t.RaiseTradeHistoryChanged(ee); } }
protected virtual SocketConnectionInfo CreateKlineWebSocket(Ticker ticker, CandleStickIntervalInfo klineInfo) { SocketConnectionInfo info = new SocketConnectionInfo(); string adress = "wss://stream.binance.com:9443/ws/" + ticker.Name.ToLower() + "@kline_" + klineInfo.Command; info.Ticker = ticker; info.KlineInfo = klineInfo; info.Adress = adress; info.Socket = new WebSocket(adress, ""); info.Socket.Error += OnKlineSocketError; info.Socket.Opened += OnKlineSocketOpened; info.Socket.Closed += OnKlineSocketClosed; info.Socket.MessageReceived += OnKlineSocketMessageReceived; info.Open(); return(info); }
public override void StopListenKlineStream(Ticker ticker, CandleStickIntervalInfo klineInfo) { SocketConnectionInfo info = GetConnectionInfo(ticker, klineInfo, KlineSockets); if (info == null) { return; } info.Socket.Error -= OnKlineSocketError; info.Socket.Opened -= OnKlineSocketOpened; info.Socket.Closed -= OnKlineSocketClosed; info.Socket.MessageReceived -= OnKlineSocketMessageReceived; info.Close(); info.Dispose(); KlineSockets.Remove(info.Socket); }
/// <summary> /// 启动服务 /// </summary> /// 时间:2016/6/7 22:54 /// 备注: /// <exception cref="System.InvalidOperationException">未能成功创建Socket服务类型。</exception> public void Start() { listener = GetCorrectSocket(); #region 解决UDP错误10054:远程主机强迫关闭了一个现有的连接 if (Protocol == SocketProtocol.UDP) { uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; listener.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } #endregion if (listener != null) { listener.Bind(this.Endpoint); if (this.Protocol == SocketProtocol.TCP) { listener.Listen(this.MaxQueuedConnections); listener.BeginAccept(new AsyncCallback(ClientConnected), listener); } else if (Protocol == SocketProtocol.UDP) { SocketConnectionInfo _connection = new SocketConnectionInfo(); _connection.Buffer = new byte[SocketConnectionInfo.BufferSize]; _connection.Socket = listener; ipeSender = new IPEndPoint(IPAddress.Any, this.Port); listener.BeginReceiveFrom(_connection.Buffer, 0, _connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), _connection); } SocketServerStartedEventArgs _arg = new SocketServerStartedEventArgs { Protocol = this.Protocol, SocketServer = this.Endpoint, StartedTime = DateTime.Now }; OnServerStarted.RaiseEvent(this, _arg); } else { throw new InvalidOperationException("未能成功创建Socket服务类型。"); } }
protected override void OnOrderBookSocketMessageReceived(object sender, MessageReceivedEventArgs e) { LastWebSocketRecvTime = DateTime.Now; SocketConnectionInfo info = OrderBookSockets[(WebSocket)sender]; const string hour24TickerStart = "[{\"e\""; const string orderBookStart = "{\"lastUpdateId\""; if (e.Message.StartsWith(hour24TickerStart)) { OnTickersSocketMessageReceived(sender, e); return; } else if (e.Message.StartsWith(orderBookStart)) { OnIncrementalOrderBookUpdateRecv(OrderBookSockets[(WebSocket)sender].Ticker, Encoding.Default.GetBytes(e.Message)); return; } }
/// <summary> /// 处理有效的socket数据接收 /// </summary> private void HanlderIsSocketConnectedDataReceived(SocketConnectionInfo connection, int bytesRead, IAsyncResult asyncResult) { if (bytesRead == 0 || (bytesRead > 0 && bytesRead < SocketConnectionInfo.BufferSize)) { byte[] _buffer = connection.Buffer; int _totalBytesRead = connection.BytesRead; connection = new SocketConnectionInfo(); connection.Buffer = new byte[SocketConnectionInfo.BufferSize]; connection.Socket = ((SocketConnectionInfo)asyncResult.AsyncState).Socket; if (this.Protocol == SocketProtocol.UDP) { connection.Socket.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection); } else if (this.Protocol == SocketProtocol.TCP) { connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), connection); } if (_totalBytesRead < _buffer.Length) { Array.Resize <byte>(ref _buffer, _totalBytesRead); } OnDataReceived.RaiseEvent(null, CreateSocketSeesion(connection, _buffer)); _buffer = null; } else { Array.Resize <Byte>(ref connection.Buffer, connection.Buffer.Length + SocketConnectionInfo.BufferSize); if (this.Protocol == SocketProtocol.UDP) { connection.Socket.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection); } else if (this.Protocol == SocketProtocol.TCP) { connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), connection); } } }
private void ClientConnected(IAsyncResult ar) { var connection = new SocketConnectionInfo(); try { connection.Socket = ((Socket)ar.AsyncState).EndAccept(ar); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, DataReceived, connection); _serverSocket.BeginAccept(ClientConnected, _serverSocket); } catch (ObjectDisposedException) { } catch (Exception exc) { FireOnError(exc); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, DataReceived, connection); _serverSocket.BeginAccept(ClientConnected, _serverSocket); } }