public override bool Connect() { try { Log.WriteLog(LogType.Info, $"SerialNetwork | Connect", $"Connect 시작"); if (SerialPort.IsOpen) { SerialPort.Close(); } SerialPort.ReadTimeout = 1000; SerialPort.WriteTimeout = 1000; SerialPort.DtrEnable = true; SerialPort.RtsEnable = true; SerialPort.DataBits = 8; SerialPort.StopBits = System.IO.Ports.StopBits.One; SerialPort.Handshake = System.IO.Ports.Handshake.None; SerialPort.Open(); Initialize(); Log.WriteLog(LogType.Info, $"SerialNetwork | Connect", $"Connect 완료"); SystemStatus.Instance.SendEventMessage(LogAdpType.HomeNet, "Success connect serial network!"); System.Threading.Thread.Sleep(100); Status = NetStatus.Connected; return(true); } catch (Exception ex) { Log.WriteLog(LogType.Error, $"SerialNetwork | Connect", $"Error : {ex.Message}"); Status = NetStatus.Disconnected; return(false); } }
private void DoNetCheckProcess() { while (true) { try { if (IsConnectedToInternet()) { var serverAddress = $"{GlobalData.Instance.ConfigManager.ServerInfo.ServerIp}"; NetStatus = PingServer(string.Empty, serverAddress) ? NetStatus.Normal : NetStatus.ConnectFail; } else { NetStatus = NetStatus.ConnectFail; } } catch (Exception ex) { NetStatus = NetStatus.Disconnect; Log.Logger.Error($"【欢迎页检测网络状态 exception】:{ex}"); MessageQueueManager.Instance.AddError("网络异常"); } Thread.Sleep(10000); } }
public bool Connect(out string error) { bool ret = false; error = "连接成功!"; try { IPAddress ip = IPAddress.Parse(_ip); var ipe = new IPEndPoint(ip, _port); _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _networkDelay * 5); _clientSocket.Connect(ipe); NetStatus = NetStatus.Good; ret = true; } catch (Exception ex) { error = ex.Message; if (ex is SocketException) { var se = ex as SocketException; } } return(ret); }
private void PingMachine(string ipAddress) { try { Ping ping = new Ping(); byte[] buffer = new byte[32]; PingOptions options = new PingOptions(); options.Ttl = 128; PingReply pingReply = ping.Send(ipAddress, 2000, buffer, options); if (pingReply.Status == IPStatus.Success) { _isOnline = true; _responseTime = pingReply.RoundtripTime; _hostName = NetStatus.GetMachineNameFromIPAddress(ipAddress); } else { _isOnline = false; _responseTime = -1; _hostName = "unavailable"; } } catch (PingException e) { Logger.Log(e.Message, MethodBase.GetCurrentMethod().Name); } catch (SocketException ex) { Logger.Log(ex.Message, MethodBase.GetCurrentMethod().Name); } }
/************************************** * CallBack 방접속 실패시 * parm (retrunCode : ? , message : ?) *****************************************/ public override void OnJoinRoomFailed(short returnCode, string message) { //방참가 실패 joinStatus = NetStatus.JoinRoom; EventConnect?.Invoke(new NetStatusEventMsg(joinStatus, false)); Debug.Log(message); }
public FEZConnect() { this.lastResetCause = GHIElectronics.NETMF.Hardware.LowLevel.Watchdog.LastResetCause; this.deviceStatus = DevStatus.Startup; this.networkStatus = NetStatus.Startup; this.lastErrorMsg = ""; }
public bool BatchRead(DeviceType type, CommandIO_Link command, out string data) { lock (_lockerSocket) { string aa; data = ""; bool ret = false; byte[] bsSend = {}; int recvRigLen = 30; int recvErrLen = 0; byte[] recvBytes = {}; string sss; bsSend = IO_LinkMasterModbusCommand.GetSendCommandBytes(type, command, ref recvRigLen).ToArray(); recvBytes = new byte[recvRigLen]; sss = byteToHexStr(bsSend); int reSendCount = 0; while (true) { reSendCount++; if (reSendCount > 3) { break; } try { aa = byteToHexStr(bsSend); _clientSocket.Send(bsSend); string bb; if (ReceiveData(ref recvRigLen, ref recvErrLen, out recvBytes)) { bb = byteToHexStr(recvBytes); ret = IO_LinkMasterModbusCommand.GetReadAnalysisReceiveByte(type, command, recvBytes, out data); break; } } catch (Exception ex) { } } if (!ret) { NetStatus = NetStatus.Cutoff; string error = ""; Connect(out error); } else { if (reSendCount == 1) { NetStatus = NetStatus.Good; } else { NetStatus = NetStatus.Block; } } return(ret); } }
protected override void OnDisconnected() { //서버에서 끊어짐.... Log.WriteLog(LogType.Info, "TcpClientNetwork| OnDisconnected", $"client disconnected a session with Id {Id}"); Status = NetStatus.Disconnected; // Wait for a while... Thread.Sleep(500); //연결 재 시도... _stopCnt += 1; if (_stopCnt >= 3) { _stop = true; } if (!_stop) { bool stt = Connect(); if (stt) { Status = NetStatus.Connected; } else { Status = NetStatus.Disconnected; } } _stopCnt = 0; }
void OnStatGUI() { GUILayout.Label("Time: " + NetworkTime.time); if (NetStatus.IsServer) { Utilities.GUIUtils.DrawHorizontalLine(1, 1, Color.black); GUILayout.Label("Num connections: " + NetworkServer.connections.Count); GUILayout.Label("Max num players: " + NetManager.maxNumPlayers); GUILayout.Label($"Dead body traffic per player: {DeadBody.DeadBodies.Sum(db => db.TrafficKbps)} Kb/s"); } if (NetStatus.IsClientActive()) { Utilities.GUIUtils.DrawHorizontalLine(1, 1, Color.black); GUILayout.Label("Ping: " + NetworkTime.rtt); GUILayout.Label("Ping send frequency: " + NetworkTime.PingFrequency); GUILayout.Label("Rtt sd: " + NetworkTime.rttSd); GUILayout.Label("Rtt var: " + NetworkTime.rttVar); GUILayout.Label("Server ip: " + NetworkClient.serverIp); GUILayout.Label("Time since last message: " + (Time.unscaledTime - NetworkClient.connection.lastMessageTime)); } GUILayout.Label($"Num spawned network objects: {NetManager.NumSpawnedNetworkObjects}"); }
public static Projectile Create( GameObject prefab, Vector3 position, Quaternion rotation, Ped shooterPed) { NetStatus.ThrowIfNotOnServer(); var go = Instantiate(prefab, position, rotation); var projectile = go.GetComponentOrThrow <Projectile>(); if (shooterPed != null) { var projectileCollider = projectile.GetComponentOrThrow <Collider>(); var pedColliders = shooterPed.GetComponentsInChildren <Collider>(); foreach (var pedCollider in pedColliders) { Physics.IgnoreCollision(pedCollider, projectileCollider); } } NetManager.Spawn(go); return(projectile); }
public static DeadBody Create(Transform ragdollTransform, Ped ped) { NetStatus.ThrowIfNotOnServer(); GameObject ragdollGameObject = Object.Instantiate(PedManager.Instance.ragdollPrefab); DeadBody deadBody = ragdollGameObject.GetComponentOrThrow <DeadBody>(); Object.Destroy(ragdollGameObject, PedManager.Instance.ragdollLifetime * Random.Range(0.85f, 1.15f)); ragdollGameObject.name = "dead body " + ped.name; ragdollTransform.SetParent(ragdollGameObject.transform); deadBody.m_framesDict = ragdollTransform.GetComponentsInChildren <Frame>() .ToDictionary(f => f.BoneId, f => new BoneInfo(f.transform)); foreach (var pair in deadBody.m_framesDict) { var rb = pair.Value.Rigidbody; if (rb != null) { deadBody.m_rigidBodiesDict.Add(pair.Key, new BoneInfo(rb.transform)); } } deadBody.InitSyncVarsOnServer(ped); NetManager.Spawn(ragdollGameObject); return(deadBody); }
public void SetConnectStatus(NetStatus status, string msg = "", bool showError = false) { if (showError && mIsEditor) { if (string.IsNullOrEmpty(msg)) { Debug.LogError("【NetConnect】prevStatus:" + mNetStatus + " changeStatus:" + status); } else { Debug.LogError("【NetConnect】prevStatus:" + mNetStatus + " changeStatus:" + status + " msg:" + msg); } } else { if (string.IsNullOrEmpty(msg)) { Debug.Log("【NetConnect】prevStatus:" + mNetStatus + " changeStatus:" + status); } else { Debug.Log("【NetConnect】prevStatus:" + mNetStatus + " changeStatus:" + status + " msg:" + msg); } } mNetStatus = status; mNetStatusMsg = msg; }
public void Connect() { if (status == NetStatus.Connected) { EDebug.Log("服务器已连接!"); OnConnectOver(); return; } string gateHost = "47.104.82.214"; int gatePort = 3101; client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(gateHost, gatePort); status = NetStatus.Connected; client.BeginReceive(readBuffer, 0, MAX_BUFFER - bufferCount, SocketFlags.None, OnReceiveCb, readBuffer); OnConnectOver(); EDebug.Log("连接上服务器了"); } catch (System.Exception e) { EDebug.Log(string.Format("服务器连接失败:\n", e.ToString())); OnDisconnect(true); throw; } }
public override void OnStatusChanged(NetStatus status) { //TODO: Implement status handling Debug.Log(status); switch (status) { case NetStatus.Connecting: break; case NetStatus.Connected: Debug.Log("Sending spawn request."); //On connect request a spawn in the world this.SendRequest(new ClaimSessionRequestPayload(), DeliveryMethod.ReliableOrdered); break; case NetStatus.EncryptionEstablished: break; case NetStatus.Disconnecting: break; case NetStatus.Disconnected: break; default: break; } }
private void OnConnectionStatusChanged(NetStatus status) { var handler = ConnectionStatusChanged; if (handler != null) { handler(this, new StatusEventArgs(status)); } }
protected override void OnWindowGUIAfterContent() { // label with status string strStatus = "Disconnected"; if (NetStatus.IsClientConnecting()) { strStatus = "Connecting."; for (int i = 0; i < ((int)Time.realtimeSinceStartup) % 3; i++) { strStatus += "."; } } else if (NetStatus.IsClientConnected()) { strStatus = "Connected"; } GUILayout.Label("Status: " + strStatus); // button for connecting/disconnecting/refreshing string buttonText = "Connect"; System.Action buttonAction = this.ConnectDirectly; if (NetStatus.IsClientConnecting()) { buttonText = "Disconnect"; buttonAction = this.Disconnect; } else if (NetStatus.IsClientConnected()) { GUI.enabled = false; buttonText = "Connected"; buttonAction = () => {}; } else { if (LanTabIndex == m_currentTabIndex) { GUI.enabled = !m_netDiscoveryHUD.IsRefreshing; buttonText = m_netDiscoveryHUD.IsRefreshing ? ("Refreshing." + new string('.', (int)((Time.time * 2) % 3))) : "Refresh LAN"; buttonAction = () => m_netDiscoveryHUD.Refresh(); } else if (InternetTabIndex == m_currentTabIndex) { GUI.enabled = !_isRefreshingMasterServerList; buttonText = _isRefreshingMasterServerList ? ("Refreshing." + new string('.', (int)((Time.time * 2) % 3))) : "Refresh servers"; buttonAction = async() => await RefreshMasterServersButtonPressed(); } } if (GUIUtils.ButtonWithCalculatedSize(buttonText, 80, 30)) { buttonAction(); } GUI.enabled = true; }
// override the OnReceive override internal NetStatus OnReceive(object sender, NetPacket pkt, object ctx) { #if DEBUG Console.Out.WriteLine("PrivateIcmpSession:OnReceived, flow capacity={0}", capacity); #endif Debug.Assert(ctx != null); NetStatus res = NetStatus.Code.PROTOCOL_OK; IcmpFormat.IcmpHeader icmpHeader = (IcmpFormat.IcmpHeader)ctx; IPFormat.IPHeader ipHeader = pkt.OverlapContext as IPFormat.IPHeader; Multiplexer mux = pkt.AdapterContext as Multiplexer; // source mux Debug.Assert(ipHeader != null && mux != null); bool handled = false; // handle various types switch (icmpHeader.type) { case (byte)IcmpFormat.IcmpType.ECHO_REQUEST: if (icmpHeader.code == 0) { #if DEBUG_IP Console.WriteLine("PrivateIcmpSession: Handling ECHO_REQUEST From: {0}", ipHeader.srcAddrIP); #endif // send reply // clone it since some session may use it (it is readonly!) int length = pkt.Length(); byte [] pktData = new byte [length]; Array.Copy(pkt.GetRawData(), 0, pktData, 0, length); IcmpFormat.CreateFastEchoReply( pktData, ipHeader.totalLength - IPFormat.Size ); NetPacket reply = new NetPacket(pktData); reply.SessionContext = this; mux.Send(reply); handled = true; } break; default: break; } // return the original packet (no use for it anymore) pkt.ReleaseRef(); // only increment the session capacity // if this is not ours.. // this way we apply back pressure and only // increase the capacity once sending is done! if (!handled) { capacity++; } #if DEBUG Console.Out.WriteLine("PrivateIcmpSession:OnReceived FINISHED, flow capacity={0}", capacity); #endif return(res); }
public bool ReceiveData(ref int recvRigLen, ref int recvErrLen, out byte[] recvBytes) { bool ret = false; recvBytes = new byte[recvRigLen]; int byteCount = 0; int count = 10; while (true) { count--; if (count < 0) { break; } try { recvRigLen = 60; var tempBytes = new byte[recvRigLen * 10]; tempBytes = _clientSocket.Receive(ref ipe); byteCount = tempBytes.Length; ret = true; recvBytes = new byte[byteCount]; Array.Copy(tempBytes, 0, recvBytes, 0, byteCount); break; } catch (Exception ex) { ret = false; if (ex is SocketException) { var se = ex as SocketException; if (se.SocketErrorCode == SocketError.WouldBlock || se.SocketErrorCode == SocketError.TimedOut) { NetStatus = NetStatus.Busy; Thread.Sleep(_networkDelay); } else if (se.SocketErrorCode == SocketError.ConnectionReset || se.SocketErrorCode == SocketError.NotConnected) { NetStatus = NetStatus.Cutoff; string error = ""; Connect(out error); } else { break; } } else { break; } } } return(ret); }
public ServerClient(RouteServer server) { Status = NetStatus.DisConnected; dtClientConnTime = DateTime.MinValue; UnitCode = ""; UnitName = ""; Routeserver = server; handler = new MsgHandler(this); }
protected virtual void OnDBRConnectStatusChanged(NetStatus status) { var handler = DBRConnectStatusChanged; if (handler != null) { handler(this, new StatusEventArgs(status)); } }
/// <summary> /// Raises UploadServerConnectionStatusChanged event. /// </summary> /// <param name="message">Received message</param> protected virtual void OnUploadServerConnectionStatusChanged(NetStatus status) { var handler = UploadServerConnectionStatusChanged; if (handler != null) { handler(this, new StatusEventArgs(status)); } }
protected override void OnWindowGUI() { m_currentTabIndex = GUIUtils.TabsControl(m_currentTabIndex, m_tabNames); GUILayout.Space(20); if (DirectTabIndex == m_currentTabIndex) { GUILayout.Label("IP:"); m_ipStr = GUILayout.TextField(m_ipStr, GUILayout.Width(200)); GUILayout.Label("Port:"); m_portStr = GUILayout.TextField(m_portStr, GUILayout.Width(100)); } else if (LanTabIndex == m_currentTabIndex) { m_netDiscoveryHUD.width = (int)this.WindowSize.x - 30; m_netDiscoveryHUD.DisplayServers(); } else if (InternetTabIndex == m_currentTabIndex) { int availableWidth = (int)this.WindowSize.x - 50; float[] widthPercentages = new float[] { 0.35f, 0.25f, 0.4f }; string[] columnNames = new string[] { "Name", "Players", "IP" }; // header GUILayout.BeginHorizontal(); for (int i = 0; i < columnNames.Length; i++) { GUILayout.Button(columnNames[i], GUILayout.Width(availableWidth * widthPercentages[i])); } GUILayout.EndHorizontal(); _masterServerScrollViewPos = GUILayout.BeginScrollView(_masterServerScrollViewPos); foreach (ServerInfo info in _serversFromMasterServer) { GUILayout.BeginHorizontal(); GUILayout.Label(info.Name, GUIUtils.CenteredLabelStyle, GUILayout.Width(availableWidth * widthPercentages[0])); GUILayout.Label($"{info.NumPlayersOnline}/{info.MaxPlayers}", GUIUtils.CenteredLabelStyle, GUILayout.Width(availableWidth * widthPercentages[1])); GUI.enabled = !NetStatus.IsClientActive(); if (GUILayout.Button($"{info.IP}:{info.Port}", GUILayout.Width(availableWidth * widthPercentages[2]))) { ConnectToServerFromMasterServer(info); } GUI.enabled = true; GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); } }
public void Reset() { this._userName = ""; this._passWd = ""; this.AutoLoginOrRegist = true; this.status = NetStatus.Disconnected; this._login = false; this._msgSend.Clear(); this._msgReceived.Clear(); }
public ServerClient(TFServer server) { Status = NetStatus.DisConnected; dtClientConnTime = DateTime.MinValue; UnitCode = ""; UnitName = ""; UnitType = ClientType.UnKnow; TFServer = server; handler = new ThreeFieldMsgHandler(this); }
/// <summary> /// 取消连接 /// </summary> public void DisConnect() { if (Status == NetStatus.Connected) { TcpClient.Client.Disconnect(false); } TcpClient.Close(); TcpClient = new TcpClient(); Status = NetStatus.DisConnected; DisConnected?.Invoke(this, new EventArgs()); }
public bool BatchWrite(string addr, int start, int count, string data) { lock (_lockerSocket) { string daa; bool ret = false; byte[] bsSend = {}; int recvRigLen = 0; int recvErrLen = 0; byte[] recvBytes = {}; recvBytes = new byte[recvRigLen]; int reSendCount = 0; while (true) { reSendCount++; if (reSendCount > 3) { break; } try { daa = byteToHexStr(bsSend); _clientSocket.Send(bsSend); if (ReceiveData(ref recvRigLen, ref recvErrLen, out recvBytes)) { ret = true; break; } } catch (Exception ex) { } } if (ret == false && data == "") { NetStatus = NetStatus.Cutoff; string error = ""; Connect(out error); } else { if (reSendCount == 1) { NetStatus = NetStatus.Good; } else { NetStatus = NetStatus.Block; } } return(ret); } }
private static void SendChatMessageToPlayerAsServer(Player player, string msg, string sender) { NetStatus.ThrowIfNotOnServer(); var chatSync = player.GetComponent <ChatSync> (); if (chatSync != null) { chatSync.SendChatMsgToClient(player.connectionToClient, msg, sender); } }
public void Close() { if (m_Socket != null && IsConnected()) { m_Socket.Shutdown(SocketShutdown.Both); m_Socket.Close(); m_Socket = null; } netStatus = NetStatus.SOCKET_TYEP_INIT; m_bConnectedFlag = false; }
/******************************* * 서버 접속 시도 *******************************/ public void Connect() { joinStatus = NetStatus.JoinServer; if (PhotonNetwork.ConnectUsingSettings()) { EventConnect?.Invoke(new NetStatusEventMsg(joinStatus, true)); } else { EventConnect?.Invoke(new NetStatusEventMsg(joinStatus, false)); } }
/***************************************** * 로비 접속 시도 *****************************************/ public void JoinLobby() { joinStatus = NetStatus.JoinLobby; if (PhotonNetwork.JoinLobby()) { EventConnect?.Invoke(new NetStatusEventMsg(joinStatus, true)); } else { EventConnect?.Invoke(new NetStatusEventMsg(joinStatus, false)); } }
public UploadServerClient() { UploadMsgHandler MsgHandler = new UploadMsgHandler(this); this.MessageRecieved += MsgHandler.Message_Recieved; strRecvMsg = ""; Status = NetStatus.DisConnected; dtClientConnTime = DateTime.MinValue; HandleRecvMsgThread = new Thread(HandleRecvMsg_Thread); HandleRecvMsgThread.Start(); }
/// <summary> /// Initializes the network stack. /// </summary> /// <param name="netSettings"></param> public void InitializeNetwork(NetSettings netSettings) { this.networkStatus = NetStatus.Startup; try { // stop network if already running if (this.networkStatus == NetStatus.Ready) { Dhcp.ReleaseDhcpLease(); Thread.Sleep(8000); // allow time for dhcp changes } // initialize tcp stack WIZnet_W5100.ReintializeNetworking(); // set IP address if (netSettings.DHCPEnabled) { // dynamic IP address Dhcp.EnableDhcp(netSettings.MACAddressBytes, netSettings.HostName); } else { // static IP address NetworkInterface.EnableStaticIP(netSettings.IPAddressBytes, netSettings.IPMaskBytes, netSettings.IPGatewayBytes, netSettings.MACAddressBytes); NetworkInterface.EnableStaticDns(netSettings.DNSAddressBytes); } this.networkStatus = NetStatus.Ready; } catch (Exception e) { this.networkStatus = NetStatus.Error; this.lastErrorMsg = e.Message; } }
/// <summary> /// Called when <see cref="NetStatus"/> <see cref="Status"/> changes. /// Can be overriden to preform actions in child classes. /// </summary> /// <param name="status">The new <see cref="NetStatus"/> of the <see cref="INetPeer"/> instance.</param> protected virtual void OnStatusChanged(NetStatus status) { //TODO: Logging if debug //TODO: Do internal handling for status change events that are ClientPeerSession specific. }
public LidgrenStatusMessage(NetConnectionStatus status) { Status = status.ToGladNet(); }
/// <summary> /// Creates a new adapter for the <see cref="IStatusMessage"/> interface. /// </summary> /// <param name="payload">Payload to adapt.</param> public PhotonStatusMessageAdapter(NetStatus status) { Status = status; }
/// <summary> /// Generates a <see cref="StatusChangePayload"/> instance with the given <see cref="NetStatus"/> /// </summary> /// <param name="status">NetStatus of the change.</param> public StatusChangePayload(NetStatus status) { Status = status; }