/// <summary> /// Secure Server Socket Status Changed Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> /// <param name="serverSocketStatus"></param> void TcpServer_SocketStatusChange(TCPServer server, uint clientIndex, SocketStatus serverSocketStatus) { try { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.myTcpServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.myTcpServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { if (ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Remove(clientIndex); } if (HeartbeatRequired && HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary[clientIndex].Stop(); HeartbeatTimerDictionary[clientIndex].Dispose(); HeartbeatTimerDictionary.Remove(clientIndex); } if (ClientReadyAfterKeyExchange.Contains(clientIndex)) { ClientReadyAfterKeyExchange.Remove(clientIndex); } if (WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Remove(clientIndex); } } } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Change Callback. Error: {0}", ex); } onConnectionChange(clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)); }
public IEnumerator ReconnectFrame(Socket sock) { bool conn = false; yield return(0); while (!conn) { try { sock.Connect(endp); conn = true; break; } catch (Exception) { } yield return(new WaitForSeconds(ReconnSpan)); } status = SocketStatus.Reconning; C_ReConnect_0x101 msg = new C_ReConnect_0x101(); LuaTable user = LuaScriptMgr.Instance.GetLuaTable("User"); msg.session_id = user.rawget("session_id") as string; Stream str = new MemoryStream(); Serializer.Serialize <C_ReConnect_0x101>(str, msg); SendProtoMessageImpl(Coo.packetManager.reconnectMessage, str); Debug.Log("network log : send reconnect proto to service..."); }
public void initServer(string IP, int port) { try { MySocksType = 2; Port = port; m_Status = SocketStatus.DisConnected; //TcpListener = new TcpListener(IPAddress.Parse(IP), port); //TcpListener.Start(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Parse(IP), port)); socket.Listen(10); g_thrAutoListenThread = new Thread(StartListen); g_thrAutoListenThread.Name = "Server listen!"; g_thrAutoListenThread.Start(); Logger.Bomb.Info("Server Start Listen!"); } catch (Exception ex) { Logger.Bomb.Error(ex.ToString()); } }
/// <summary> /// SocketStatusChange Callback /// </summary> /// <param name="client"></param> /// <param name="clientSocketStatus"></param> void Client_SocketStatusChange(SecureTCPClient client, SocketStatus clientSocketStatus) { if (ProgramIsStopping) { ProgramIsStopping = false; return; } try { Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus)); OnConnectionChange(); // The client could be null or disposed by this time... if (Client == null || Client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { HeartbeatStop(); OnClientReadyForcommunications(false); // socket has gone low CheckClosedAndTryReconnect(); } } catch (Exception ex) { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException); } }
/// <summary> /// TCP Server (Unsecure) Socket Status Change Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> /// <param name="serverSocketStatus"></param> void UnsecureServer_SocketStatusChange(TCPServer server, uint clientIndex, SocketStatus serverSocketStatus) { Debug.Console(2, "Client at {0} ServerSocketStatus {1}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex), serverSocketStatus.ToString()); if (server.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED) { if (SharedKeyRequired && !WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Add(clientIndex); } if (!ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Add(clientIndex); } } else { if (ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Remove(clientIndex); } if (HeartbeatRequired && HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary.Remove(clientIndex); } } if (UnsecureServer.ServerSocketStatus.ToString() != Status) { onConnectionChange(); } }
private void ReadLoop(Socket socket) { if (socket.Connected) { ReadData rd = readpool.Get(); rd.socket = socket; try { socket.BeginReceive(rd.buffer, rd.read, rd.total - rd.read, SocketFlags.None, ReadEnd, rd); } catch (Exception ex) { Debug.LogException(ex); status = SocketStatus.Errored; socket.Shutdown(SocketShutdown.Both); socket.Close(); socket = null; } } else { status = SocketStatus.Errored; socket = null; } }
public void Update() { switch (status) { case SocketStatus.Ready: status = SocketStatus.Ok; connectSignal.Dispatch(); ReadLoop(socket); break; case SocketStatus.Ok: HandlePacket(); break; case SocketStatus.Errored: status = SocketStatus.Reconn; disconnectSignal.Dispatch(); Reconnect(); break; case SocketStatus.ReReady: status = SocketStatus.Ok; reconnectSignal.Dispatch(); ReadLoop(socket); if (outqueue.Count > 0) { BeginSend(); } break; default: break; } }
private void setStatus(SocketStatus s, string msg = null, TcpClient tcp = null) { if (_status == s) { return; } _status = s; if (s == SocketStatus.DISCONNECT) { if (tcp != null) { if (tcp.GetStream() != null) { tcp.GetStream().Close(); } tcp.Close(); } if (msg != null) { Debug.Log(msg); showMessageTip(msg); } _tcpclient = null; } if (_onStatus != null) { _onStatus(_status); } }
public CustomSocket(OnData onData, OnStatus onStatus) { this._onData = onData; this._onStatus = onStatus; this._status = SocketStatus.UNDEFINE; }
public TcpSocketAccept(SocketStatus status, TcpSocket socket, TcpSocket connection, TcpSocketAcceptParse parse) { this.status = status; this.socket = socket; this.connection = connection; this.parse = parse; }
private void OnStatusChange(SocketStatus status) { if (TCPStatusChange != null) { TCPStatusChange(status); } }
private void setStatus(SocketStatus s, string msg = null, TcpClient tcp = null) { if (_status == s) { return; } _status = s; if (s == SocketStatus.DISCONNECT) { if (tcp != null) { if (tcp.GetStream() != null) { tcp.GetStream().Close(); } tcp.Close(); } if (msg != null) { Debug.Log(msg); ClientResponse temp = new ClientResponse(); temp.headCode = APIS.TIP_MESSAGE; temp.message = msg; _onData(temp); } _tcpclient = null; } if (_onStatus != null) { _onStatus(_status); } }
/// <summary> /// Socket Status Change Handler /// </summary> /// <param name="client"></param> /// <param name="clientSocketStatus"></param> void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus) { Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText); if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED && !DisconnectCalledByUser && AutoReconnect) { WaitAndTryReconnect(); } // Probably doesn't need to be a switch since all other cases were eliminated switch (clientSocketStatus) { case SocketStatus.SOCKET_STATUS_CONNECTED: Client.ReceiveDataAsync(Receive); DisconnectCalledByUser = false; break; } var handler = ConnectionChange; if (handler != null) { ConnectionChange(this, new GenericSocketStatusChageEventArgs(this)); } // Relay the event //var handler = SocketStatusChange; //if (handler != null) // SocketStatusChange(this); }
public IEnumerator ConnectFrame(Socket sock, IPEndPoint ep) { bool conn = false; while (!conn) { try { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " ConnectFrame sock.Connect(ep) pre ReconnSpan=" + ReconnSpan); sock.Connect(ep); conn = true; Debug.Log(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " ConnectFrame conn=" + conn); break; } catch (Exception ex) { Debug.Log(ex); HDebugger.LogException(HDebuggerModule.Proto, ex); conn = false; } yield return(new WaitForSeconds(ReconnSpan)); } status = SocketStatus.Ok; rdata = readpool.Get(); rdata.socket = sock; Debug.Log("CommonSocketServer connect status=" + status); sConnect.Dispatch(sid); }
// // public void ConnectSocket() // { // Connect(url, port); // } public IEnumerator ConnectFrame(Socket sock, IPEndPoint ep) { bool conn = false; while (!conn) { try { sock.Connect(ep); conn = true; break; } catch (Exception ex) { Debug.LogException(ex); conn = false; } yield return(new WaitForSeconds(ReconnSpan)); } status = SocketStatus.Ok; rdata = readpool.Get(); rdata.socket = sock; sConnect.Dispatch(); }
public void Pause() { lock (_asyncLock) { _asyncState |= SocketStatus.Pause; } }
public TcpSocketSend(SocketStatus status, int count, TcpSocket socket, SocketBuffer buffer) { this.status = status; this.count = count; this.socket = socket; this.buffer = buffer; }
/// <summary> /// 连接制定ip和端口 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> public void Connect(string ip, int port) { m_connectStartTime = TimeUtils.CurLocalTimeMilliSecond(); m_status = SocketStatus.Connecting; m_active = false; m_netReader.Clear(); m_netSender.Clear(); m_canTargetEvent = true; PackageOut.ResetIndex(); lock (this) { sendCout = 0; } try { IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, port); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, SEND_TIME_OUT); m_socket.BeginConnect(ipEndpoint, new AsyncCallback(M_ConnectCallBack), m_socket); } catch (Exception) { Debug.LogError("服务器关闭,请稍后重试"); m_socket.Close(); m_status = SocketStatus.Closed; } }
private void ProcessReceive(SocketAsyncEventArgs e) { if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { byte[] buffer = _recvBuffer; if (IsAccepted) { _lastUpdate = DateTime.Now.AddMinutes(1); } lock (Buffer) { Buffer.Enqueue(buffer, 0, e.BytesTransferred); } _manager.Enqueue(this); lock (_asyncLock) { _asyncState &= ~SocketStatus.Pending; } } else { Dispose(); } }
public void ClientSend(byte[] byteArray) { try { socket.Send(byteArray); string str = "Send byte[], Lenght = " + byteArray.Length; Logger.socket.Info(str); APISocksEventArgs mye = new APISocksEventArgs(); mye.msg = str; if (Sending != null) { Sending(this, mye); } } catch (Exception ex) { Logger.Bomb.Error(ex.ToString()); StopRecive = true; m_Status = SocketStatus.DisConnected; APISocksEventArgs mye = new APISocksEventArgs(); mye.msg = ""; mye.status = SocketStatus.DisConnected; if (StatusChange != null) { StatusChange(this, mye); } Connect(); } }
protected virtual void OnStatusChanged(TCPClient mytcpclient, SocketStatus clientsocketstatus) { var handler = StatusChanged; if (handler != null) { try { #if DEBUG if (clientsocketstatus == SocketStatus.SOCKET_STATUS_CONNECTED) { Debug.WriteSuccess(GetType().Name + " Connected", "IP: " + mytcpclient.AddressClientConnectedTo); } else { Debug.WriteWarn(GetType().Name, "Socket status = " + clientsocketstatus); } #endif handler(mytcpclient, clientsocketstatus); } catch (Exception e) { CloudLog.Exception(e); } } }
/// <summary> /// 创建通讯并连接 /// </summary> /// <param name="IP">远程IP地址</param> /// <param name="Port">远程端口号</param> /// <param name="TimeOut">收发超时时间</param> /// <param name="IfTimeOutLooseAtBegin">起始段是否放大超时时间</param> protected void CreatClient(string IP, int Port, int TimeOut, bool IfTimeOutLooseAtBegin = false) { remoteIP = IP; remotePort = Port; socketTimeout = TimeOut; ifTimeOutLooseAtBegin = IfTimeOutLooseAtBegin; remoteSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 通讯超时时间 if (ifTimeOutLooseAtBegin) { remoteSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, socketTimeout * looseMaxProp); remoteSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, socketTimeout * looseMaxProp); looseCount = 0; } else { remoteSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, socketTimeout); remoteSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, socketTimeout); } remoteIpe = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort); if (remoteSocketStatus == SocketStatus.UnCreated) { remoteSocketStatus = SocketStatus.Created; } // 只在socket实例化的时候连接一次 remoteSocket.Connect(remoteIpe); remoteSocketStatus = SocketStatus.Connected; }
private void socketStatusChanged(IntPtr customObject, IntPtr sockRef, SocketStatus status, [MarshalAs(UnmanagedType.LPStr)] string msg) { this.Dispatcher.Invoke(new Action(delegate() { txtSockLog.Text = msg; })); }
/// <summary> /// 连接上服务器 /// </summary> void OnConnect(IAsyncResult asr) { try { //TcpClient tcpclient = asr.AsyncState as TcpClient; if (client.Connected) { client.EndConnect(asr); outStream = client.GetStream(); client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), outStream); status = SocketStatus.CONNECT; //ExecuteSocketStatusEvent(); } else { status = SocketStatus.CONNECT_FAIL; Close(); //ExecuteSocketStatusEvent(); } } catch (Exception ex) { Debug.LogError(ex.Message); } }
private void OnSocketStatusChanged(IntPtr customObject, IntPtr socketRef, SocketStatus status, [MarshalAs(UnmanagedType.LPStr)] string msg) { // status changed _IsSocketConnected = (status == SocketStatus.CS_Running); _btnConnectString = _IsSocketConnected?"Disconnect":"Connect"; Debug.Log(msg); }
public void Connect() { lock (this) { if (this.EndPoint == null) throw new InvalidOperationException("EndPoint must be set."); if (this.Status != SocketStatus.Disconnected) throw new InvalidOperationException("You can't connect if the socket isn't disconnected"); Log.Debug("Connect"); if (this.Client.IsDisposed()) { this.Client = new TcpClient(); } this.Client.Connect(this.EndPoint); this.Status = SocketStatus.Connected; } this.CallOnConnectionEvent(this.FirstConnection ? SocketConnectionEvent.Connected : SocketConnectionEvent.Reconnected); this.FirstConnection = false; var bundle = new SocketReceiveBundle(this.Client); this.Client.Client.BeginReceive( bundle.Buffer, 0, SocketReceiveBundle.BufferSize, SocketFlags.None, this.EndReceive, bundle); }
public void ConnectToServer() { try { Logger.Bomb.Info("Connect to " + IP + ":" + Port.ToString()); while (true) { try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_Status = SocketStatus.DisConnected; socket.Connect(IP, Port); // 1.設定 IP:Port 2.連線至伺服器 if (socket.Connected) { m_Status = SocketStatus.Connected; APISocksEventArgs mye = new APISocksEventArgs(); mye.msg = ""; mye.status = SocketStatus.Connected; if (StatusChange != null) { StatusChange(this, mye); } StopRecive = false; ReciveThread = new Thread(Reciver); ReciveThread.IsBackground = true; ReciveThread.Name = "Client " + IP.ToString(); ReciveThread.Start(); isConnecting = false; break; } Thread.Sleep(3000); } catch (Exception ex) { StopRecive = true; Thread.Sleep(3000); } if (StopConnect) { isConnecting = false; break; } } } catch (Exception ex) { isConnecting = false; Logger.Bomb.Error(ex.ToString()); } }
public void Init(string host, int port, int index, bool littleEnd) { try { //if (inited) if (tcpSession != null) { tcpSession.Close(); tcpSession = null; } //if (!inited) { adapter = new NetAdapter(); adapter.SetEndianness(littleEnd); netClientId = index; socketStatus = SocketStatus.NotConnet; currentHost = host; currentPort = port; IPAddress ipEndPoint = IPAddress.Parse(currentHost); IPEndPoint ipEnd = new IPEndPoint(ipEndPoint, currentPort); tcpSession = new AsyncTcpSession(ipEnd); tcpSession.Connected += onConnected; tcpSession.Closed += onClosed; tcpSession.Error += onError; tcpSession.DataReceived += OnDataReceive; } } catch (System.Exception e) { Debugger.LogError("net client init exception->" + host + "^" + port + "^" + index + "^" + littleEnd + "^" + e.ToString()); } inited = true; }
//===================// Event Handlers //===================// //-------------------------------------// // Function | clientSocketChange // Description | Event handler for TCP client socket status. If socket disconnects, function // attempts to reconnect and starts timer to re-attempt connection every 15s. // Also sends connection status (H/L) to S+. If connected, begins listening for // incoming data from server, then notifies RTS class so that information can // be requested from server if a meeting is in progress. //-------------------------------------// internal static void clientSocketChange(TCPClient _cli, SocketStatus _status) { Debug(String.Format("Socket State is {0}", (int)_status)); if (_status == SocketStatus.SOCKET_STATUS_NO_CONNECT || _status == SocketStatus.SOCKET_STATUS_CONNECT_FAILED || _status == SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY || _status == SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY || _status == SocketStatus.SOCKET_STATUS_LINK_LOST) { serverConnected = false; serverConnecting = false; queryInProgress = false; ServerErrorEvent(0); if (okToConnect) { ServerConnect(); } } else if (_status == SocketStatus.SOCKET_STATUS_CONNECTED) { serverConnected = true; serverConnecting = false; Debug("Server connected!"); client.ReceiveDataAsync(clientDataRX); RTS.ServerConnectedCallback(); } }
public UdpSocketReceive(SocketStatus status, int count, UdpSocket socket, SocketBuffer buffer, byte[] address) { this.status = status; this.count = count; this.socket = socket; this.buffer = buffer; this.address = address; }
void OnSocketStatusChange(TCPClient client, SocketStatus clientSocketStatus) { if (clientSocketStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { this.Status = SocketStatus.SOCKET_STATUS_LINK_LOST; ErrorLog.Warn("TCP Client to {0} link lost - {1} Link Down!", client.AddressClientConnectedTo, client.EthernetAdapter); } }
/// <summary> /// Constructor /// </summary> /// <param name="socket">socket object (must be already connected)</param> /// <param name="handler">callback handler (can be null if no handler is specified)</param> public PlainSocket(Socket socket, IDataHandler handler) { _handler = handler ?? new NullDataHandler(); _socket = socket; Debug.Assert(_socket.Connected); _socketStatus = SocketStatus.Ready; _data = new DataFragment(0x1000); }
private void DoClose() { lock (_sync) { if (_socketStatus == SocketStatus.Closed) { return; } _socket.Shutdown(SocketShutdown.Both); _socket.Close(); _socketStatus = SocketStatus.Closed; } }
protected AbstractGranadosSocket(IDataHandler h) { _handler = h; _single = new byte[1]; _socketStatus = SocketStatus.Unknown; }
public void Setup(TcpClient client, ISocketMessageProcessor processor) { lock (this) { if(client == null)throw new ArgumentNullException("client"); if (processor == null) throw new ArgumentNullException("processor"); if (this.Status != SocketStatus.Disconnected) throw new InvalidOperationException("You can't setup a socket if it isn't disconnected."); Log.DebugFormat("Setup {0}",client.Client.RemoteEndPoint); this.EndPoint = client.Client.RemoteEndPoint as IPEndPoint; this.MessageProcessor = processor; this.Client = client; this.Status = SocketStatus.Connected; } this.CallOnConnectionEvent(this.FirstConnection ? SocketConnectionEvent.Connected : SocketConnectionEvent.Reconnected); this.FirstConnection = false; var bundle = new SocketReceiveBundle(this.Client); this.Client.Client.BeginReceive( bundle.Buffer, 0, SocketReceiveBundle.BufferSize, SocketFlags.None, this.EndReceive, bundle); }
/// <summary> /// Close connection /// </summary> public void Close() { lock (_sync) { if (_socketStatus == SocketStatus.Closed) { return; } _socket.Shutdown(SocketShutdown.Both); _socket.Close(); _socketStatus = SocketStatus.Closed; } FireOnClosed(); }
public void Disconnect() { lock (this) { if (this.Status == SocketStatus.Disconnected) return; this.Status = SocketStatus.Disconnected; System.Threading.Thread.Sleep(200); } Log.Debug("OnDisconnect"); try { this.Client.Close(); } catch { } //this.Client = null; this.MessageProcessor.Clear(); this.CallOnConnectionEvent(SocketConnectionEvent.Disconnected); }
public virtual void OnSocketStatusChanged( SocketStatus status, string msg ) { }