看了上篇socket入门,相信你已经对socket有一定的了解了http://www.cnblogs.com/nsky/p/4501782.html
现在来回顾一下。上篇在循环接收客户端连接和循环接收消息的两个方法。都使用了多线程,因为Accept()方法是同步的,所有用了多线程异步执行。
1 static void Main(string[] args) 2 { 3 string ip = "192.168.1.2"; 4 int points = 8000; 5 6 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 7 IPAddress address = IPAddress.Parse(ip); 8 IPEndPoint point = new IPEndPoint(address, points); 9 10 socket.Bind(point); 11 socket.Listen(10); 12 Console.WriteLine("服务器已经启动,等待连接"); 13 socket.Accept(); //阻塞主线程 14 Console.WriteLine("需要等待客户端连接,我才会执行"); 15 Console.ReadLine(); 16 }
当运行界面后。
当有客户端连接后
提到同步和异步,想必大家都不陌生。AJAX有同步异步请求,委托有同步异步方法,多线程也有同步异步。同理。对于socket通信,也存在异步通信。
异步通信监听主要是这两个方法:
BeginAccept()和EndAccept()方法
所以把上面的方法稍做修改后
1 static void Main(string[] args) 2 { 3 string ip = "192.168.1.2"; 4 int points = 8000; 5 6 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 7 IPAddress address = IPAddress.Parse(ip); 8 IPEndPoint point = new IPEndPoint(address, points); 9 10 socket.Bind(point); 11 socket.Listen(10); 12 Console.WriteLine("服务器已经启动,等待连接"); 13 //socket.Accept(); //阻塞主线程 14 //Console.WriteLine("需要等待客户端连接,我才会执行"); 15 16 socket.BeginAccept(new AsyncCallback(Listen), socket); 17 18 Console.WriteLine("这里不会阻塞了"); 19 20 21 22 Console.ReadLine(); 23 } 24 static void Listen(IAsyncResult result) 25 { 26 Socket client = (Socket)result.AsyncState; 27 Socket cy = client.EndAccept(result); 28 Console.WriteLine(cy.RemoteEndPoint + "连接成功"); 29 }
运行看。这是客户端没连接器的效果,很显然没有被阻塞了
当有客户端连接成功。则会执行Listen方法
那么客户端连接的也是一样的
BeginConnect()和EndConnect()方法
1 static void Main(string[] args) 2 { 3 string ip = "192.168.1.2"; 4 int points = 8000; 5 6 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 7 8 IPAddress address = IPAddress.Parse(ip); 9 10 IPEndPoint point = new IPEndPoint(address, points); 11 12 Console.WriteLine("正在连接:" + address); 13 socket.BeginConnect(point, new AsyncCallback(Connect), socket); 14 15 Console.ReadLine(); 16 } 17 static void Connect(IAsyncResult result) 18 { 19 Socket client = result.AsyncState as Socket; 20 client.EndConnect(result); 21 Console.WriteLine(client.RemoteEndPoint.ToString()); 22 }
时间: 2024-11-08 15:41:41