Socket同步编程
服务器端代码using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;namespace Server{ public class Server { private static string data = null; /// <summary> /// 开始监听 /// </summary> public static void StartListening() { byte[] buffer = new byte;//用来缓冲 //设置服务器端Socket IPHostEntry ipHostInfo = Dns.GetHostByName(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList; IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1111); Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化一个Socket listener.Bind(ipEndPoint);//绑定 listener.Listen(10);//设置最大监听数量 while (true) { Console.WriteLine("服务器正等待客户端的连接"); Socket server = listener.Accept();//会一直阻塞,直到有客户端连接 while (true) { int rec = server.Receive(buffer); data += Encoding.ASCII.GetString(buffer, 0, rec); if(data.IndexOf("<EOF>")>-1) { break; } } Console.WriteLine("接收到的客户端数据是:{0}",data); //将收到的数据再发给客户端 buffer = Encoding.ASCII.GetBytes(data); server.Send(buffer); server.Shutdown(SocketShutdown.Both); server.Close(); } } static void Main(string[] args) { StartListening(); } }}
客户端代码
sing System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;namespace Client{ class Client { public static void StartClient() { byte[] buffer = new byte; //服务器的地址 IPAddress ipAddress = IPAddress.Parse("114.214.60.253"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1111); //连接服务器 Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ipEndPoint); //发送数据 byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); int send=client.Send(msg); //接受数据 int rec = client.Receive(buffer); Console.WriteLine("客户端接收到的数据是:{0}",Encoding.ASCII.GetString(buffer,0,rec)); Console.Read(); } static void Main(string[] args) { StartClient(); } }}
页:
[1]