010 socket定义服务器
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SocketServer { class Program { /// <summary> /// 服务器: /// 1、接收请求 /// 2、接收数据 /// 3、发送数据 /// 4、断开连接 /// </summary> /// public static Socket serverSocket; static void Main(string[] args) { //AddressFamily 地址族 //SocketType 套接字类型 //ProtocolType 协议 serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//地址族,套接字类型,协议 //Socket ServerSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);//UDP使用Dgram数据报类型套接字 //进行绑定 //端口号范围0~65535 IPEndPoint endPoint = new IPEndPoint(IPAddress.Any,9999); serverSocket.Bind(endPoint); serverSocket.Listen(10);// //开启一个线程接受客户端 Thread thread = new Thread(listenClientConnect); thread.Start(); } /// <summary> /// 监听客户端连接 /// </summary> private static void listenClientConnect() { //等待 有客户端连接的时候 就会触发这个函数,返回一个客户端的socket对象 Socket clientSocket = serverSocket.Accept(); Console.WriteLine("客户端连接成功 信息:"+clientSocket.AddressFamily.ToString()); //给客户端发送一个消息(发送字节数据) clientSocket.Send(Encoding.Default.GetBytes("服务器告诉你连接成功了"));//GetBytes字符串转字节数据 //接受客户端发来的消息 Thread recThread = new Thread(receiveClientMessage); recThread.Start(clientSocket); } /// <summary> /// 接受来自客户端的消息 /// </summary> /// <param name="clientSocket"></param> private static void receiveClientMessage(object clientSocket) { Socket socket = clientSocket as Socket;//接收到的对象转换类型 byte[] buffer = new byte[1024]; //接收到数据的长度 int length = socket.Receive(buffer); //显示出来 Console.WriteLine(Encoding.Default.GetString(buffer, 0, length)); } } }