本篇博客主要讲述的异步的问题。首先明确异步到底是什么东东,异步就是发起一个指令,并不需要一直等待指令的执行结果,而是可以继续忙其他的事情。
一、异步连接
服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace TCPServer
{
class Program
{
private const int portNum = 19939;
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, portNum);
listener.Start();
bool isDone = false;
while(!isDone)
{
TcpClient client = listener.AcceptTcpClient();
if(client!=null)
{
Console.WriteLine("接收到一个客户端了 "+client.Client.RemoteEndPoint);
}
}
listener.Stop();
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Text;
namespace TCPClient
{
class Program
{
private const string hostName = "127.0.0.1";
private const int portNum = 19939;
static void Main(string[] args)
{
try
{
TcpClient client = new TcpClient();
client.BeginConnect(hostName, portNum, OnConnected, "hello world");
}
catch(Exception e)
{
Console.WriteLine("网络异常!");
}
}
static void OnConnected(IAsyncResult ar)
{
object obj = ar.AsyncState;
}
}
}
运行服务端,调试客户端:
over!