/// <summary> /// 세션을 초기화 한다 /// 세션은 재활용될 수 있으므로 재활용을 고려하여야 한다 /// </summary> /// <param name="info">초기화시 정보</param> public void Init(SessionInitializeInfo info) { _receivedPacketQueue = new BufferBlock <NetPacket>(); _cts = new CancellationTokenSource(); int low = Guid.NewGuid().GetHashCode(); long high = (long)Guid.NewGuid().GetHashCode() << 32; _connectId = (long)low | high; State = SessionState.Initialized; if (_tcpChannel != null) { _tcpChannel.Init(_cts); _tcpChannel.SetSocket(info.AcceptedTcpSocket); } if (_udpChannel != null) { _udpChannel.Init(_cts); _udpChannel.SetSocket(info.UdpServiceSocket); } }
/// <summary> /// 서버로 연결을 시도합니다 /// </summary> /// <param name="timeout">타임아웃</param> /// <returns>성공여부</returns> public async Task <bool> ConnectAsync(TimeSpan?timeout = null) { if (_socket != null || State != SessionState.Closed) { return(false); } try { State = SessionState.Initialized; TimeSpan currentTimeout = timeout ?? TimeSpan.FromSeconds(10); _cts = new CancellationTokenSource(); _serverEndPoint = NetUtil.GetEndPoint(_clientOption.TcpServerAddress, _clientOption.TcpServerPort); _serverUdpEndPoint = NetUtil.GetEndPoint(_clientOption.UdpServerAddress, _clientOption.UdpServerPort); if (_clientOption.IsServiceUdp) { _udpSocket = new UdpSocketEx( _loggerFactory.CreateLogger("ClientUdpSocket"), OnPreProcessUdpRawData, UdpSocketReceiveRawAsyncObject); _udpSocket.CreateClient(); } _isUdpConnected = false; _socket = new Socket(SocketType.Stream, ProtocolType.Tcp); await _socket.ConnectAsync(_serverEndPoint).TimeoutAfter(currentTimeout); if (_socket.Connected == false) { _logger.LogInformation("Fail to connect"); State = SessionState.Closed; _socket.Close(); _socket = null; return(false); } if (_tcpChannel != null) { _tcpChannel.Init(_cts); _tcpChannel.PacketReceived = OnReceiveFromChannel; _tcpChannel.SetSocket(_socket); } if (_udpChannel != null) { _udpChannel.Init(_cts); _udpChannel.PacketReceived = OnReceiveFromChannel; if (_udpSocket != null) { _udpChannel.SetSocket(_udpSocket); _udpChannel.LocalEndPoint = _udpSocket.GetLocalEndPoint(); } } RunAsync().DoNotAwait(); if (_clientOption.IsServiceUdp) { currentTimeout = TimeSpan.FromSeconds(10); while (IsUdpConnected == false && State == SessionState.Initialized) { await Task.Delay(100); currentTimeout -= TimeSpan.FromMilliseconds(100); if (currentTimeout < TimeSpan.FromMilliseconds(0)) { throw new Exception("udp connection timeout"); } } } OnSessionConnected(); _logger.LogInformation("Connect succeed"); return(true); } catch (Exception ex) { OnError(ex); Close(); } State = SessionState.Closed; return(false); }