C# 网络编程 socket编程入门

socket服务端

		private static Socket serverSocket = null;

        static void Main(string[] args)
        {
            //AddressFamily.InterNetwork 地址族
            //SocketType.Stream 指定类型
            //ProtocolType.Tcp 指定协议
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //进行绑定
            //端口号范围 0-65535
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);
            serverSocket.Bind(endPoint);
            //10 代表连接队列的最大长度
            serverSocket.Listen(10);
            //开一个线程接收客户端连接
            Console.WriteLine("开始监听");
            Thread thread = new Thread(listenClientConnect);
            thread.Start();

            while (true) { }
        }

        /// 
        /// 监听客户端连接
        /// 
        private static void listenClientConnect()
        {
            //等待 有客户端连接的时候 就会触发这个函数 返回一个客户端的socket对象
            Socket clientSocket = serverSocket.Accept();
            Console.WriteLine("客户端连接成功 信息:" + clientSocket.AddressFamily.ToString());
            //给客户端发送一个消息
            clientSocket.Send(Encoding.Default.GetBytes("服务器告诉你连接成功了"));
            Thread recThread = new Thread(receiveClientMessage);
            recThread.Start(clientSocket);
        }

        /// 
        /// 接收来自客户端的消息
        /// 
        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));
        }

socket客户端

        private static Socket clientSocket = null;

        static void Main(string[] args)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //客户端要连接 不需要bind
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
            clientSocket.Connect(remoteEP);
            Console.WriteLine("连接到远程服务器");

            byte[] result = new byte[1024];
            int length = clientSocket.Receive(result);
            Console.WriteLine("收到消息 : " + Encoding.Default.GetString(result, 0, length));

            clientSocket.Send(Encoding.Default.GetBytes("服务器你好 我是客户端"));


            while (true) { }
        }

你可能感兴趣的:(C#,网络编程,c#,socket)