/// <summary> /// Starts connecting to another socket /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="timeoutMillis"></param> /// <returns></returns> public IClientSocket Connect(string ip, int port, int timeoutMillis) { _ip = ip; _port = port; if (_socket != null && _socket.IsConnected) { _socket.Close(); } _isConnected = false; Status = EConnectionStatus.Connecting; if (_peer != null) { _peer.MessageReceived -= HandleMessage; _peer.Dispose(); } _socket = new WebSocket(new Uri(string.Format("ws://{0}:{1}/w", ip, port))); var peer = new PeerWs(_socket); peer.MessageReceived += HandleMessage; _peer = peer; Peer = peer; CoroutineHelper.StartCoroutine(_socket.Connect()); return(this); }
/// <summary> /// Starts connecting to another socket /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="timeoutMillis"></param> /// <returns></returns> public IClientSocket Connect(string ip, int port, int timeoutMillis, string key = "") { if (ip == "0.0.0.0") { int sss = 0; } _ip = ip; _port = port; _key = key; Status = EConnectionStatus.Connecting; if (_peer != null) { _peer.MessageReceived -= HandleMessage; _peer.Dispose(); } if (_netManager == null) { InitEvents(); } _netManager.Connect(_ip, _port, _key); return(this); }
private void InitEvents() { _listener = new EventBasedNetListener(); _listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) => { _peer.HandleDataReceived(dataReader.GetRemainingBytes(), 0); dataReader.Recycle(); }; _listener.PeerConnectedEvent += (peer) => { Status = EConnectionStatus.Connected; var pe = new PeerLn(peer); pe.SetConnectedState(true); pe.MessageReceived += HandleMessage; _peer = pe; Peer = pe; Connected?.Invoke(); }; _listener.PeerDisconnectedEvent += (peer, disconnectInfo) => { if (Peer != null) { Peer.MessageReceived -= HandleMessage; } _peer?.SetConnectedState(false); Status = EConnectionStatus.Disconnected; Disconnected?.Invoke(); }; _netManager = new NetManager(_listener) { DisconnectTimeout = 300000 }; _netManager.Start(); }
/** * <summary> Set GUI state </summary> * <param name="status"> Status to apply </param> */ private void SetGuiState(EConnectionStatus status) { switch (status) { case EConnectionStatus.Open: gbLoopback.Enabled = true; tbFpgaIpAddress.Enabled = false; tbFpgaRxPort.Enabled = false; tbHostRxPort.Enabled = false; lFpgaIpAddress.Enabled = false; lFpgaRxPort.Enabled = false; lHostRxPort.Enabled = false; bOpenClose.Text = "Close"; break; case EConnectionStatus.Closed: gbLoopback.Enabled = false; tbFpgaIpAddress.Enabled = true; tbFpgaRxPort.Enabled = true; tbHostRxPort.Enabled = true; lFpgaIpAddress.Enabled = true; lFpgaRxPort.Enabled = true; lHostRxPort.Enabled = true; bOpenClose.Text = "Open"; break; default: throw new ArgumentOutOfRangeException("Illegl status passed"); } }
private void OnConnected(IAsyncResult result) { try { result.AsyncWaitHandle.Close(); if (m_socket.Connected) { Debug.Log("Connect Sucess..."); //结束异步连接请求 m_socket.EndConnect(result); //开始异步等待数据 m_socketTag++; m_socketRecvArgs = new SocketAsyncEventArgs(); m_socketRecvArgs.UserToken = m_socketTag; m_socketRecvArgs.Completed += new EventHandler <SocketAsyncEventArgs>(AsyncCompleteNotify); m_socketRecvArgs.SetBuffer(m_socketRecvBuffer, 0, m_socketRecvBuffer.Length); m_socketSendArgs = new SocketAsyncEventArgs(); m_socketSendArgs.UserToken = m_socketTag; m_socketSendArgs.Completed += new EventHandler <SocketAsyncEventArgs>(AsyncCompleteNotify); m_socketSendArgs.SetBuffer(m_socketSendBuffer, 0, m_socketSendBuffer.Length); m_socket.ReceiveAsync(m_socketRecvArgs); m_connectState = EConnectionStatus.Connected; } } catch (Exception ex) { Debug.LogError("Connect Fail:" + ex.Message); m_connectState = EConnectionStatus.Conected_Failed; } }
private void SetStatus(EConnectionStatus status) { switch (status) { case EConnectionStatus.Connecting: if (Status != EConnectionStatus.Connecting) { Status = EConnectionStatus.Connecting; } break; case EConnectionStatus.Connected: if (Status != EConnectionStatus.Connected) { Status = EConnectionStatus.Connected; CoroutineHelper.StartCoroutine(_peer.SendDelayedMessages()); if (Connected != null) { Connected.Invoke(); } } break; case EConnectionStatus.Disconnected: if (Status != EConnectionStatus.Disconnected) { Status = EConnectionStatus.Disconnected; if (Disconnected != null) { Disconnected.Invoke(); } } break; } }
/****************************************************************************************/ /* Constructors */ /****************************************************************************************/ /** * <summary> Constructor </summary> */ public MainForm() { InitializeComponent(); m_connectionStatus = EConnectionStatus.Closed; m_packetSize = 100; m_packetCount = 2; m_timeoutMs = 1000; }
public void Connect(string ip, int port) { Close(); if (string.IsNullOrEmpty(ip)) { Debug.LogError("Empty IP Address to Connect...."); return; } ip = ip.Trim(); try { if (c_Support_IPV6) { IPAddress[] addr = Dns.GetHostAddresses(ip); if (addr == null || addr.Length <= 0) { Debug.LogError("Invalid server Ip:" + ip); Close(); return; } if (addr[0].AddressFamily == AddressFamily.InterNetworkV6) { m_socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } m_socket.SendBufferSize = c_Async_Send_Buffer_Size; m_socket.ReceiveBufferSize = c_Async_Recv_Buffer_Size; m_socket.BeginConnect(addr, port, null, this); } else { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SendBufferSize = c_Async_Send_Buffer_Size; m_socket.ReceiveBufferSize = c_Async_Recv_Buffer_Size; m_socket.BeginConnect(ip, port, null, this); } m_connectState = EConnectionStatus.Conecting; Debug.Log(string.Format("Try Connect -- {0}:{1}", ip, port)); } catch (Exception ex) { Debug.LogError(ex.Message); Close(); } }
public FakeClient(uint game_version, uint user_index, string username, ulong steam_id) { this.raknet_client = new Facepunch.Network.Raknet.Client(); this.raknet_client.cryptography = this; this.raknet_client.callbackHandler = this; this.game_version = game_version; this.user_index = user_index; this.username = username; this.steam_id = steam_id; this.steam_token = Token.CreateToken(this.steam_id); this.connection_status = EConnectionStatus.DISCONNECTED; this.lastMessageMillis = 0; }
/* Callbacks */ public void OnNetworkMessage(Message message) { if (message.type == Message.Type.RequestUserInformation) { Console.WriteLine("[User {0}] Sending user information", this.user_index); if (this.raknet_client.write.Start()) { this.raknet_client.write.PacketID(Message.Type.GiveUserInformation); this.raknet_client.write.UInt8(228); this.raknet_client.write.UInt64(this.steam_id); this.raknet_client.write.UInt32(this.game_version); this.raknet_client.write.String("windows"); this.raknet_client.write.String(this.username); this.raknet_client.write.String("public"); this.raknet_client.write.BytesWithSize(this.steam_token); this.raknet_client.write.Send(new SendInfo()); } } else if (message.type == Message.Type.Approved) { Console.WriteLine("[User {0}] Connection approved", this.user_index); if (this.raknet_client.write.Start()) { this.raknet_client.write.PacketID(Message.Type.Ready); ProtoBuf.ClientReady protobuf_client_ready = new ProtoBuf.ClientReady { clientInfo = new List <ProtoBuf.ClientReady.ClientInfo>() }; protobuf_client_ready.WriteToStream(this.raknet_client.write); this.raknet_client.write.Send(new SendInfo()); } message.connection.decryptIncoming = true; message.connection.encryptOutgoing = true; message.connection.encryptionLevel = 1; this.connection_status = EConnectionStatus.CONNECTED; } else if (message.type == Message.Type.ConsoleCommand) { Console.WriteLine("[User {0}] ConsoleCommand: {1}", this.user_index, message.read.String()); } else if (message.type == Message.Type.ConsoleMessage) { Console.WriteLine("[User {0}] ConsoleMessage: {1}", this.user_index, message.read.String()); } }
/// <summary> /// Starts connecting to another socket /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="timeoutMillis"></param> /// <returns></returns> public IClientSocket Connect(string ip, int port, int timeoutMillis, string key = "") { _ip = ip; _port = port; _isConnected = false; Status = EConnectionStatus.Connecting; if (_peer != null) { _peer.MessageReceived -= HandleMessage; _peer.Dispose(); } _listener = new EventBasedNetListener(); _listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) => { _peer.HandleDataReceived(dataReader.GetRemainingBytes(), 0); dataReader.Recycle(); }; _listener.PeerConnectedEvent += (peer) => { _isConnected = false; var pe = new PeerLn(peer); pe.SetConnectedState(true); pe.MessageReceived += HandleMessage; _peer = pe; Peer = pe; Connected?.Invoke(); }; _listener.PeerDisconnectedEvent += (peer, disconnectInfo) => { _peer?.SetConnectedState(false); _isConnected = false; Disconnected?.Invoke(); }; _netManager = new NetManager(_listener) { DisconnectTimeout = 300000 }; _netManager.Start(); _netManager.Connect(_ip, _port, key); return(this); }
public void Close() { m_connectState = EConnectionStatus.Closed; if (m_socket == null) { return; } try { if (m_socket.Connected) { m_socket.Shutdown(SocketShutdown.Both); } m_socket.Close(); m_socket = null; } catch (Exception ex) { Debug.LogError(ex.Message); } }
/** * <summary> Open connection </summary> */ private void OpenConnection() { //Create socket information IPAddress fpgaIpAddr; try { fpgaIpAddr = IPAddress.Parse(tbFpgaIpAddress.Text); } catch (FormatException) { throw new Exception("Illegal IP-Address entered"); } Int32 fpgaPort; try { fpgaPort = Int32.Parse(tbFpgaRxPort.Text); } catch (FormatException) { throw new Exception("Illegal FPGA Rx Port entered"); } m_fpgaEndPoint = new IPEndPoint(fpgaIpAddr, fpgaPort); try { m_localPort = Int32.Parse(tbHostRxPort.Text); } catch (FormatException) { throw new Exception("Illegal Host Rx Port entered"); } //Update GUI m_connectionStatus = EConnectionStatus.Open; SetGuiState(EConnectionStatus.Open); }
public void HandleIncomingMessage(byte[] bytesReceived) { var msg = Encoding.UTF8.GetString(bytesReceived); msg = msg.Remove(msg.IndexOf(END_OF_MESSAGE)); Logger.Log(this.ToString() + "Message received '--" + msg + "--'"); var blocks = msg.Split(MESSAGE_SEPARATOR.ToCharArray(), 2); //block[0] - technical message //block[1] - other message var technicalMessage = Helper.StringToEnum<ETechnicalMessages>(blocks[0], ETechnicalMessages.None); Logger.Log("technicalMessage: '" + technicalMessage.ToString()+ "'"); if (status != EConnectionStatus.Disconnected) { switch (technicalMessage) { case ETechnicalMessages.Abort: { Status = EConnectionStatus.Disconnected; if(null != OnDisconnected) OnDisconnected(); Logger.Log("Disconnected: " + (blocks.Length == 2 ? blocks[1] : "No explanation")); break; } case ETechnicalMessages.Ping: { lastMessageTimeStamp = DateTime.Now; Pong(); break; } case ETechnicalMessages.Pong: { if (status != EConnectionStatus.TimedOut) { Logger.LogWarning(string.Format("status = {0}, but connection received Pong", status)); lastMessageTimeStamp = DateTime.Now; Status = EConnectionStatus.Connected; } break; } case ETechnicalMessages.Connect: { lastMessageTimeStamp = DateTime.Now; Status = EConnectionStatus.Connected; SendTechicalMessage(ETechnicalMessages.Approved); break; } case ETechnicalMessages.Approved: { lastMessageTimeStamp = DateTime.Now; Status = EConnectionStatus.Connected; break; } case ETechnicalMessages.InternalMessage: { lastMessageTimeStamp = DateTime.Now; Status = EConnectionStatus.Connected; if(blocks.Length == 2 && null != OnMessageReceived) OnMessageReceived(blocks[1]); break; } default: { Logger.LogWarning("Unknown state: " + msg); break; } } } }
private void GameClient_ConnectionStatusChanged(GClient sender, CSteamID server, EConnectionStatus status) { Debug.LogFormat("Server: {0} Connection Status: {1}", server.m_SteamID, status); }
/** * <summary> Close connection </summary> */ private void CloseConnection() { m_connectionStatus = EConnectionStatus.Closed; SetGuiState(EConnectionStatus.Closed); }
public void OnClientDisconnected(string reason) { this.connection_status = EConnectionStatus.DISCONNECTED; Console.WriteLine("[User {0}] Disconnected with reason: {1}", this.user_index, reason); }
public void DisconnectFromServer(string reason) { this.raknet_client.Disconnect(reason, true); this.connection_status = EConnectionStatus.DISCONNECTED; }
public void Disconnect(string message) { Logger.Log("Disconnect with message :" + message); SendTechicalMessage(ETechnicalMessages.Abort, message); Status = EConnectionStatus.Disconnected; if(null != OnDisconnected) OnDisconnected(); }
public void ConnectToServer(string ip, int port) { Console.WriteLine("[User {0}] Connecting to {1}:{2}", this.user_index, ip, port); this.raknet_client.Connect(ip, port); this.connection_status = EConnectionStatus.CONNECTING; }
public void Connect() { this.Status = EConnectionStatus.Connecting; SendTechicalMessage(ETechnicalMessages.Connect); }