System.Net.Sockets.SocketException:'提供了无效的参数'
_socket.Connect(Dns.GetHostAddresses("vcap.me"), 1832);
完整代码:
namespace App.Root.Core.Network.Sockets
{
class SocketHandler
{
private readonly Socket _socket;
private readonly Timer _timer;
public SocketHandler()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_timer = new Timer(OnTick, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
private void Connect()
{
if (IsConnected())
{
return;
}
_socket.Connect(Dns.GetHostAddresses("vcap.me"), 1832);
}
private bool IsConnected()
{
return !((_socket.Poll(1000, SelectMode.SelectRead) && (_socket.Available == 0)) || !_socket.Connected);
}
private void OnTick(object obj)
{
if (!IsConnected())
{
CoreUtilities.LogToConsole("Connecting to the server...");
Connect();
}
}
}
}
我所做的就是初始化SocketHandler构造函数。
答案 0 :(得分:0)
问题是Timer正在创建一个单独的线程,它正忙于处理第一个线程,因此它无法在第二个线程内连接。