From b4abaf36dca5c29037c62ceb70932a148f89dfaf Mon Sep 17 00:00:00 2001 From: Souryo Date: Wed, 10 Feb 2016 20:19:06 -0500 Subject: [PATCH] NetPlay: Mesen no longer hangs for 10+ seconds when trying to connect to a ip/port that doesn't respond --- GUI.NET/Forms/frmMain.cs | 4 +++- Utilities/Socket.cpp | 27 ++++++++++++++++++--------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/GUI.NET/Forms/frmMain.cs b/GUI.NET/Forms/frmMain.cs index 216521c4..cd9d7eb1 100644 --- a/GUI.NET/Forms/frmMain.cs +++ b/GUI.NET/Forms/frmMain.cs @@ -620,7 +620,9 @@ namespace Mesen.GUI.Forms } else { frmClientConfig frm = new frmClientConfig(); if(frm.ShowDialog(sender) == System.Windows.Forms.DialogResult.OK) { - InteropEmu.Connect(ConfigManager.Config.ClientConnectionInfo.Host, ConfigManager.Config.ClientConnectionInfo.Port, ConfigManager.Config.Profile.PlayerName, ConfigManager.Config.Profile.PlayerAvatar, (UInt16)ConfigManager.Config.Profile.PlayerAvatar.Length, ConfigManager.Config.ClientConnectionInfo.Spectator); + Task.Run(() => { + InteropEmu.Connect(ConfigManager.Config.ClientConnectionInfo.Host, ConfigManager.Config.ClientConnectionInfo.Port, ConfigManager.Config.Profile.PlayerName, ConfigManager.Config.Profile.PlayerAvatar, (UInt16)ConfigManager.Config.Profile.PlayerAvatar.Length, ConfigManager.Config.ClientConnectionInfo.Spectator); + }); } } } diff --git a/Utilities/Socket.cpp b/Utilities/Socket.cpp index 997e1dab..123580e1 100644 --- a/Utilities/Socket.cpp +++ b/Utilities/Socket.cpp @@ -127,20 +127,29 @@ bool Socket::Connect(const char* hostname, uint16_t port) std::cout << "Failed to resolve hostname." << std::endl; SetConnectionErrorFlag(); } else { - // Setup our socket address structure - u_long iMode = 0; + //Set socket in non-blocking mode + u_long iMode = 1; ioctlsocket(_socket, FIONBIO, &iMode); // Attempt to connect to server - if(connect(_socket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen) == SOCKET_ERROR) { - std::cout << "Failed to establish connection with server." << std::endl; - SetConnectionErrorFlag(); - } else { - iMode = 1; - ioctlsocket(_socket, FIONBIO, &iMode); + connect(_socket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen); + fd_set writeSockets; + writeSockets.fd_count = 1; + writeSockets.fd_array[0] = _socket; + + //Timeout after 3 seconds + TIMEVAL timeout; + timeout.tv_sec = 3; + timeout.tv_usec = 0; + + // check if the socket is ready + if(select(0, nullptr, &writeSockets, nullptr, &timeout)) { result = true; - } + } else { + //Could not connect + SetConnectionErrorFlag(); + } freeaddrinfo(addrInfo); }