首页 > 代码库 > 服务器可用的Socket

服务器可用的Socket

string portNo = "1999";
            IPAddress ServerIp = IPAddress.Parse("112.124.46.251");
            IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(portNo));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            byte[] byteMessage = new byte[100];
            try
            {
                socket.Bind(iep);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            while (true)
            {
                try
                {
                   
                  
                    socket.Listen(1);
                    Socket newSocket = socket.Accept();
                   
                    newSocket.Receive(byteMessage);
                    string msg = Encoding.Default.GetString(byteMessage);
                    msg = msg.TrimEnd(\0);
                   SocketMessageSave saveInfo = new SocketMessageSave();
                    //BaseClass.OperateData("insert into temp_tb(信息)values(‘"+msg+"‘)");
                   saveInfo.IntoData(msg);
                   newSocket.Send(Encoding.ASCII.GetBytes("ok"));  
                }
                catch (SocketException ex)
                {
                    socket.Close();
                }
            }