首页 > 代码库 > socket编程

socket编程

 

            int port = 6000; //服务器端口 

            string host = "127.0.0.1"; //服务器IP

            IPAddress ip = IPAddress.Parse(host); //将string格式的服务器IP解析为IPAddress类型         

            IPEndPoint ipe = new IPEndPoint(ip, port);  //IPEndPoint类对象通过组合服务器IP和Port形成服务连接点

            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立socket实例,AddressFamily.InterNetwork表示IPV4,SocketType.Stream表示套接字类型,ProtocolType.Tcp协议类型            

            sSocket.Bind(ipe); //绑定ipe到socket实例sSocket          

            sSocket.Listen(0);   //使socket处于监听状态            

            Console.WriteLine("监听已经打开,请等待");

            //receive message            

            Socket serverSocket = sSocket.Accept();  //收到客户端对服务器请求,则简历服务器socket实例,用于接受客户端请求,此时连接建立        

            Console.WriteLine("连接已经建立");          

            string recStr = "";  //接收到的字符串           

            byte[] recByte = new byte[4096];         

            int bytes = serverSocket.Receive(recByte, recByte.Length, 0); //服务器socket接受数据,保存在recByte数组中,返回接收到的字符数       

            recStr += Encoding.ASCII.GetString(recByte, 0, bytes);

            //send message            

           Console.WriteLine("服务器端获得信息:{0}", recStr);          

           string sendStr = "send to client :hello";  //发回客户端的字符串    

           byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);         

           serverSocket.Send(sendByte, sendByte.Length, 0);           

           serverSocket.Close();  //关闭服务器socket         

           sSocket.Close();       //关闭socket

 

 

            int port = 6000;                   

            string host = "127.0.0.1";//服务器端ip地址

            IPAddress ip = IPAddress.Parse(host);    

            IPEndPoint ipe = new IPEndPoint(ip, port);

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

            clientSocket.Connect(ipe);    //发出连接请求

            //send message        

            string sendStr = "send to server : hello,ni hao";       

           byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);      

           clientSocket.Send(sendBytes);  //向服务器发送字符串

            //receive message             string recStr = "";        

           byte[] recBytes = new byte[4096];      

           int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);  //接收从服务器发回的字符串      

           recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);       

           Console.WriteLine(recStr);   //将受到的字符串显示在屏幕上       

           clientSocket.Close();

socket编程