This article mainly introduces C # socket programming to implement UDP client, we refer to the use of the bar
The code is as follows: Console.WriteLine ("This is a Client, the host name is {0}", Dns.gethostname ()); Set the server endpoint IPEndPoint ipe = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 8001); Create sockets to connect to the server, specify network type, data connection type and network protocol socket Connsocket = new socket (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); String welcome = "Client Message:hello!!!"; byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes (welcome); Send test message connsocket.sendto (data, data) to the server. Length, Socketflags.none, IPE); IPEndPoint Server = new IPEndPoint (ipaddress.any, 0); Service endpoint EndPoint Remote = (EndPoint) server; data = new byte[1024]; For IP addresses that do not exist, the blocking mode limit//server can be unblocked within a specified time after this line of code is joined. SetSocketOption (Socketoptionlevel.socket, socketoptionname.receivetimeout, 100); int recv = Connsocket.receivefrom (data, ref Remote); Print information sent back from the server Console.WriteLine ("message received from {0}:", remote.tostring ()); Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); while (true)//can send a message to the server in real time { string input = Console.readlINE (); if (input = = "Exit")//Interrupt link { Connsocket.sendto (Encoding.ASCII.Get Bytes (input), Remote); data = new byte[1024]; recv = connsocket.receivefrom (data, ref Remote); Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); break; } Else { Connsocket.sendto (Encoding.ASCII.GetBytes) Client message: "+ input", Remote); data = new byte[1024]; recv = connsocket.receivefrom (data, ref Remote); Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); }} Console.WriteLine ("Stopping Client."); Connsocket.close ();