//Mensaje recibido del server private static void OnReceive(SocketReader read, byte[] data) { //Debug.Log("[OnRecive]: " + data[0] + " [0]\n"); packets.Add(data); KeepAliveReceived(); SocketReader.Begin(SocketClient.socket, OnReceive, OnError); }
// Connect the client to the server public static bool ConnectToServer() { bool ok = false; lastErrorMsg = ""; try { if (SocketClient.socket == null) { SocketClient.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000); // The socket will linger for 1 seconds after Socket.Close is called. //LingerOption lingerOption = new LingerOption (true, 1); //socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); //SocketClient.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); //SocketClient.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); //if(!SocketClient.socket.Connected) { lastErrorMsg = "Attempting connection to NIC [" + ip + ":" + port + "]"; Debug.Log(lastErrorMsg); SocketClient.socket.Connect(server); } //else //Debug.Log("ConnectToServer()::Connected: true"); //ok = true; } else { if (!SocketClient.socket.Connected) //either this side is not connected { //let's try again Debug.Log("Socket disconnected. Cleaning up for a retry"); //Debug.Log("Attempting connection to: "+ip + " " + port); //SocketClient.socket.Shutdown(SocketShutdown.Both); //SocketClient.socket.Disconnect (true); SocketClient.socket = null; //SocketClient.socket.Connect (server); lastErrorMsg = "Socket is connected, but server did not answer"; } else if (unansweredKeepAlives > 5) //or the other one does not answer yet { SocketClient.socket.Shutdown(SocketShutdown.Both); //Debug.Log("shutd"); SocketClient.socket.Disconnect(true); //SocketClient.socket.Disconnect(false); Debug.Log("Socket Shutdown and Dced"); SocketClient.socket = null; ok = false; lastErrorMsg = "Server at " + ip + ":" + port + " not responding"; } } } catch (SocketException s) { Debug.Log("Error connecting to: " + ip + " " + port + " (" + s.ErrorCode + ")"); if (lastErrorMsg.Length == 0) { lastErrorMsg = "{" + ip + ":" + port + "} " + s.Message; } //SocketClient.socket.Shutdown(SocketShutdown.Both); //Debug.Log("shutd"); //SocketClient.socket.Disconnect(true); //SocketClient.socket.Disconnect(false); //SocketClient.socket = null; return(false); } if (SocketClient.socket != null && SocketClient.socket.Connected) { //everything went better than expected =) Debug.Log("Connected to " + ip + " on port " + port + " using port " + ((IPEndPoint)SocketClient.socket.LocalEndPoint).Port.ToString()); //lastErrorMsg = ""; //packets = new List<string>(); packets = new List <byte[]>(); // Start listening to the port SocketReader.Begin(SocketClient.socket, OnReceive, OnError); ok = true; unansweredKeepAlives = 0; } return(ok); }