首页 > 技术文章 > 服务器可用的Socket

vienna 2014-05-01 18:48 原文

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();
                }
            }

 

推荐阅读