.Net网络编程——服务端获取客户端连接

来源:互联网 发布:sql数据修复工具 编辑:程序博客网 时间:2024/06/05 14:49



一,客户端服务端连接图示







         其中,在客户端和服务端的socket中,都报存这连接的信息;客户端通过connect连接,服务端可以调用AcceptTcpClient来获取链接到服务端的客户端,每一个客户端和服务端的连接都对应这唯一一个Socket.




二,服务端获取连接示例



using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Net.Sockets;namespace 获取单一客户端连接{    class Program    {        static void Main(string[] args)        {            #region 获取单一客户端连接                //Console.WriteLine("服务端启动啦啦啦。。");                //IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });                //TcpListener listener = new TcpListener(ip, 8500);                //listener.Start();                //Console.WriteLine("服务端开始监听8500。。。。");                ////获取一个连接,中断方法                //TcpClient remoteClient = listener.AcceptTcpClient();//获取一个与客户端的连接,同时它返回一个TcpClient类型示例,此时它所包装的是由服务端去往客户端的socket(这是一个block method)                ////打印连接到客户端的信息                //Console.WriteLine("客户端连接成功。本地:{0}------>客户端{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);            #endregion            #region 获取多个客户端的连接                Console.WriteLine("服务端启动啦啦啦。。");                IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });                TcpListener listener = new TcpListener(ip, 8500);                listener.Start();                Console.WriteLine("服务端开始监听8500。。。。");                while (true)                {                    /*                        将服务端放入一个始终执行的循环中。                                          */                    //获取一个连接,中断方法                    TcpClient remoteClient = listener.AcceptTcpClient();//获取一个与客户端的连接,同时它返回一个TcpClient类型示例,此时它所包装的是由服务端去往客户端的socket(这是一个block method)                    //打印连接到客户端的信息                    Console.WriteLine("客户端连接成功。本地:{0}------>客户端{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);                }                                       #endregion        }    }}



            PS:AcceptTcpClient是一个同步的方法,对比AJAX的异步,可以发现如果服务端获取不到客户端的连接,就会一直阻塞在这里,而不是像AJAX请求数据的时候,下面的东西可以继续,成功后回调。










0 0