Socket编程服务端和客户端代码

//服务器端Socket程序 建一个main程序接受客户端的消息 public void ServerSocket() { Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//(1)首先在服务器端定义一个套接字(socket),使用Tcp协议 listener.Bind(new IPEndPoint(IPAddress.Any, 2112));//(2)其次设定该套接字的绑定IP,接受从任意IP地址发往端口2112的消息 listener.Listen(100);//(3)将套接字置为监听状态,并设置监听队列为100 while (true) //死循环,即不发生异常中断的情况下一直接受消息 { string receiverAllStr = string.Empty; Socket socket = listener.Accept();//(4)Create a new Socket for a newly created connection while (true) { byte[] receiveBytes = new byte[1024]; int numBytes = socket.Receive(receiveBytes); //(5)从socket中接受消息,将接收到的消息写入已定义的字节数组中 string receiveStr = Encoding.ASCII.GetString(receiveBytes, 0, numBytes); receiverAllStr += receiveStr; if (receiveStr.IndexOf("[FINAL]") > -1) { Console.WriteLine(receiverAllStr); break; } } string replySuccess = "The data can be successfullly received!";//非必须 byte[] byteStr = Encoding.ASCII.GetBytes(replySuccess);//非必须 socket.Send(byteStr);//非必须,给客户端发送一个接受成功的回复 send data to connected System.Net.Sockets.Socket socket.Shutdown(SocketShutdown.Both);//(6)Disables sends and receives on a System.Net.Sockets.Socket socket.Close();//(7)关闭socket Connection,释放所有已占用资源,在死循环内继续接受其他消息 } listener.Close(); //Close System.Net.Sockets.Socket connection and release all associated resources. Console.Read(); } //客户端的socket程序 新建一个main程序来运行发送程序 public void ClientSocket() { Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//(1)首先在服务器端定义一个套接字(socket),使用Tcp协议 IPHostEntry ipHost=Dns.Resolve("127.0.0.1"); IPAddress ipAddress=ipHost.AddressList[0]; IPEndPoint ipEndPoint=new IPEndPoint(ipAddress,2112); sender.Connect(ipEndPoint);//(2)其次设定该套接字的链接IP,发送到指定IP地址的2112端口 string sendStr = "hello, the socket test!"; byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr+"[FINAL]"); sender.Send(sendBytes);//(3)发送数据比特流 byte[] receiveBytes=new byte[1024]; sender.Receive(receiveBytes);//(4)获取服务器的响应数据 Console.WriteLine("received from server: " + Encoding.ASCII.GetString(receiveBytes)); sender.Shutdown(SocketShutdown.Both);//(5)Disables sends and receives on a System.Net.Sockets.Socket sender.Close();//(6)关闭socket Connection,释放所有已占用资源 }

 

你可能感兴趣的:(编程,socket,String,tcp,服务器,byte)