socket的初入门(一)

先说下服务端吧如下

        private static void Service()

        {

            int revc = 0;

            byte[] mess = new byte[9999];

            IPEndPoint oIPEndPoint = new IPEndPoint(IPAddress.Any, 9999);

            Socket oSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            oSocket.Bind(oIPEndPoint);//开始监听的服务端IP

            oSocket.Listen(100);//挂起的列队长度

            Console.WriteLine("等待客户端介入....");

            Socket oSocketClient = oSocket.Accept();//当有客户端连接的时候返回一个新的socket给他使用通信

            IPEndPoint oIPEndPointClient = (IPEndPoint)oSocketClient.RemoteEndPoint;//获取服务器的IP和端口

            Console.WriteLine("客户端:"+oIPEndPointClient.Address+"端口:"+oIPEndPointClient.Port+"进入服务器");

            string strWelcome = "欢迎进入";

            mess = Encoding.UTF8.GetBytes(strWelcome);

            oSocketClient.Send(mess,mess.Length,SocketFlags.None);//发送消息

            while (true)

            {

                try

                {

                    mess = new byte[1024];

                    revc = oSocketClient.Receive(mess);

                    if (revc == 0)

                    {

                        break;

                    }

                    Console.WriteLine(Encoding.UTF8.GetString(mess, 0, revc));

                    oSocketClient.Send(mess, revc, SocketFlags.None);

                }

                catch (Exception)

                {

                   break;

                }

            }



            Console.WriteLine("断开连接:"+oIPEndPointClient.Address);

            oSocketClient.Close();

            oSocket.Close();

            Console.ReadLine();



        }

  然后是客户端

        private static void Client()

        {

            byte[] data = new byte[9999];

            

            Socket oSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            Console.WriteLine("请输入服务端IP");

            string strIP = Console.ReadLine();

            Console.WriteLine("请输入端口");

            int iPost = Convert.ToInt32(Console.ReadLine());

            IPEndPoint oIPEndPoint = new IPEndPoint(IPAddress.Parse(strIP), 9999);

            try

            {

                oSocket.Connect(oIPEndPoint);

            }

            catch (Exception ex)

            {

                Console.WriteLine("无法连接服务器,错误原因:"+ex.Message);

                return;

            }

            int revc = oSocket.Receive(data);

            Console.WriteLine(Encoding.UTF8.GetString(data, 0, revc));

            while (true)

            {

                oSocket.Send(Encoding.UTF8.GetBytes(Console.ReadLine()));

                data = new byte[9999];

                oSocket.Shutdown(SocketShutdown.Both);

            }

 

            oSocket.Close();

            Console.ReadLine();

        }

  现在问题是客户端点X关闭之后服务端就异常了,异常原因是因为服务端在死循环去获取客户端的信息,客户端突然消失了让服务端爆发了异常。没想到如何解决,找百度大神看看有资料没。

你可能感兴趣的:(socket)