class Program { private static byte[] result = new byte[1024]; private static int myProt = 8885;//端口 static Socket serverSocket; public delegate void Print(string str); public void MyPrint(string str) { Console.WriteLine(str); } public delegate void Calc(int num1, int num2); public void MyCalc(int num1,int num2) { Console.WriteLine("输出两个数字的计算之和:{0}",(num1+num2)); } static void Main(string[] args) { Program pro = new Program(); Print print = pro.MyPrint; print("dfsdf"); Calc calc = pro.MyCalc; calc(3, 4); //int i = 0; //while(i>-1) //{ // Console.WriteLine("输入两个数字:"); // string str_num1 = Console.ReadLine(); // string str_num2 = Console.ReadLine(); // Console.WriteLine("输出两数之和:"+(Convert.ToInt32(str_num1)+Convert.ToInt32(str_num2))); //} //IPAddress ip = IPAddress.Parse("127.0.0.1"); //serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //serverSocket.Bind(new IPEndPoint(ip, myProt)); //serverSocket.Listen(10); //Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()); //Thread mythread = new Thread(ListenClient); //mythread.Start(); //Console.ReadLine(); ////服务器IP地址 //IPAddress ip = IPAddress.Parse("127.0.0.1"); //serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ; //serverSocket.Bind(new IPEndPoint(ip, myProt));//绑定IP地址:端口 //serverSocket.Listen(10);//设定最多10个排队连接请求 //Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()); ////通过clientsocket发送数据 //Thread myThread = new Thread(ListenClientConnect); //myThread.Start(); //Console.ReadLine(); } //监听客户端连接 private static void ListenClientConnect() { while (true) { Socket clientsocket = serverSocket.Accept(); //string sendMessage = Console.ReadLine(); //clientsocket.Send(Encoding.ASCII.GetBytes(sendMessage)); clientsocket.Send(Encoding.ASCII.GetBytes("server say hello")); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientsocket); } } private static void ListenClient() { while(true) { Socket client = serverSocket.Accept(); client.Send(Encoding.ASCII.GetBytes("Hello")); Thread receive = new Thread(ReceiveMessage); } } //接收消息 private static void ReceiveMessage(object clientSocket) { Socket myClientSocket = (Socket)clientSocket; while (true) { try { //通过clientsocket接收数据 int num = myClientSocket.Receive(result); Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, num)); } catch (Exception ex) { Console.WriteLine(ex.Message); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } } } }
委托和接口很类似,但是委托只用于方法。