public async Task ConnectWithServer1(string ip, int port)
{
Socket TcpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, port);
try
{
await Task.Run(() =>
{
TcpClient1.Connect(ipEnd);
});
return true;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return false;
}
问题很多矛盾的地方,虽然我们明白你的意思,但是毛病太多,我们也无法准确说出你到底需要什么写法,只能一步一步分析
1.代码本身就无法通过,既然声明是Task ,那么return true/false 这句通不过
单纯这里我们建议修改为
public Task ConnectWithServer1(string ip, int port)
{
Socket TcpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, port);
//单就这一句我们直接返回task,不用管true还是false
return Task.Run(() => { TcpClient1.Connect(ipEnd); });
}
2。如果需要管true,false,无需纠结楼上那些回复,你写的本身就对,只需要修改 task为泛型bool的task(扩展知识:TaskCompletionSource自己研究,俺们不多说)
public static async Task<bool> ConnectWithServer1(string ip, int port)
{
Socket TcpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, port);
try
{
await Task.Run(() =>
{
TcpClient1.Connect(ipEnd);
});
return true;
}
catch (Exception e)
{
return false;
}
}
//调用
var r= await ConnectWithServer1("192.168.99.101", 1883);
3.上面是根据你的代码修改,下面是如果我自己来写,我会写成什么样
public static async Task<bool> ConnectWithServer1(string ip, int port)
{
Socket TcpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//原本就支持异步连接,所以直接用
await TcpClient1.ConnectAsync(ip, port);
return true;
}
catch (Exception e)
{
return false;
}
}
调用Connect会先进行链接,结果无论链接是否成功,都会return true;当链接过程出现异常时,会进入异常处理,return false
Connect是阻塞的吧
如果是的话那你这个代码应该不管连不连都是true了
其次看看connect的返回值 应该有链接成功返回true吧
谢谢各位的回复 我已经搞定了 现在贴出来给大家看下,希望对大家能有帮助:
public async Task ConnectWithServer1(string ip, int port)
{
Socket TcpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, port);
return await Task.Run(() =>
{
try
{
TcpClient1.Connect(ipEnd);
return true;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return false;
}
});
}