In. NET technology, there are many techniques for service programming, such as sockets, Windows Service,. NET remoting, Message queue, Web Service, WCF, and so on, which are often closely related to network knowledge. Sometimes the combination of multithreading and other technologies to achieve specific needs. This is only a socket for example, see how to use C # for network programming.
Familiar with socket programming should not be unfamiliar, to achieve a socket, a service-side program and a client program, server-side program binding IP, port, set up listening, client program to establish a connection, to the server to throw a request, through the TCP or UDP protocol, to obtain service side feedback, This is the process of a duplex communication. And most importantly, the socket communication is not related to the specific programming language, C, C + +, JAVA, C #, PHP, Flex and other advanced programming languages provide the corresponding implementation.
The following is a simple example of a client socket, also used in the actual work. At the time, the socket server was a Java-developed program that allows two machines of different networks to get information from the front-end machine by using a socket. After the client initiates the request, the server listens to the request, responds to it, and returns the encapsulated XML document to the client. After the client receives the XML data, it resolves the processing.
/// <summary> ///get the data that the communication middleware sends through the socket, DataTable/// </summary> /// <param name= "Requestcode" >Request Code</param> /// <param name= "Array" >conditions of the query, encapsulated in an array</param> /// <param name= "ErrMsg" >Error Hints</param> /// <returns>after a series of processed DataTable</returns> PublicDataTable getdatatable (stringRequestcode, ilist<string> list, out stringerrmsg) { Try { stringIP = configurationmanager.appsettings["IP"]. ToString (). Trim ();//the IP address of the middleware intPort = Convert.ToInt32 (configurationmanager.appsettings["Port"]. ToString (). Trim ());//the port number of the middlewareIPEndPoint ServerIP =NewIPEndPoint (Ipaddress.parse (IP), port); using(Socket Clientsocket =NewSocket (ServerIP. AddressFamily, SocketType.Stream, protocoltype.tcp)) {clientsocket.connect (ServerIP);
//Socket connection Specifies middleware front-facing machine stringOutbufferstring =string. Empty;//ready to send the message Switch(requestcode) { Case "111001": outbufferstring= Preparesendpackets ("111001", list); Break; Case "111002": outbufferstring= Preparesendpackets ("111002", list); Break; Case "111003": outbufferstring= Preparesendpackets ("111003", list); Break; default: Break; } byte[] Outbuffer =New byte[2048]; Outbuffer= Encoding.GetEncoding ("GBK"). GetBytes (outbufferstring); Clientsocket.send (Outbuffer, Outbuffer.length,0);//Send a delivery paper byte[] Inbuffer =New byte[51200]; Clientsocket.receive (Inbuffer, Inbuffer.length,0);//Receiving Messages stringInbufferstring ="<?xml version= ' 1.0 ' encoding= ' gb2312 '?>"; Inbufferstring+ = Encoding.GetEncoding ("GBK"). GetString (Inbuffer); DataTable DT= Parsingpackets (Requestcode, inbufferstring, outerrmsg); returnDT; } } Catch(Exception ex) {Throwex; } }
Attach a small example of a complete point.
This program simply implements the process by which the client sends a message and the server receives the message and feeds the message to the client. With the synchronous mode, it is the simplest model of socket communication.
Server console:
Static voidMain (string[] args) { //define a dictionary to hold a list of usersdictionary<string,string> users =Newdictionary<string,string>(); using(Socket socket =Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp)) {IPEndPoint ipe=NewIPEndPoint (Ipaddress.parse ("192.168.1.7"),1234); Socket. Bind (IPE); Socket. Listen (Ten); Console.WriteLine ("Socket start!"); while(true)//Service End-of-life loop, constantly providing socket service{Socket Clientsocket= socket. Accept ();//waiting for client requestsIPEndPoint IP=(IPEndPoint) clientsocket.remoteendpoint; stringremoteaddress = IP. Address.tostring ();//Remote IP Address byte[] Revbytes =New byte[ +]; Clientsocket.receive (revbytes);//receiving messages sent by the client stringuser =Encoding.Default.GetString (revbytes); if(!users. ContainsKey (remoteaddress)) {users. ADD (remoteaddress, user); } Console.WriteLine ("from the"+ remoteaddress +"of users:"+user); stringContent ="Welcome to the world of sockets! "; byte[] bytes =Encoding.Default.GetBytes (content); Clientsocket.send (bytes);//sending a server-side message to the clientClientsocket.shutdown (Socketshutdown.both); Clientsocket.close (); } } }
Client WPF:
PublicMainWindow () {InitializeComponent (); } Private stringip//Incoming IP Private stringUsername//the incoming user name PublicMainWindow (stringIpstringusername) {InitializeComponent (); This. IP =IP; This. Username =username; } Private voidButton1_Click (Objectsender, RoutedEventArgs e) {sendsocketpackge (); } Private StaticSocket client;//Socket Object /// <summary> ///sending a packet/// </summary> Private voidsendsocketpackge () {//set up 1 socket objects to initiate a TCP connectionClient =Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Client. Connect (Ipaddress.parse ("192.168.1.7"),1234);//connect to server designated IP and port stringUsersays = Username +"said:"+ This. TextBox1.Text;//username himself with a string instead ofClient. Send (Encoding.Default.GetBytes (usersays));//Sends the current user name to the server side byte[] bytes =New byte[ +]; Client. Receive (bytes);//receive messages sent by the service sideclient. Shutdown (Socketshutdown.both); Client. Close (); stringContent =string. Join (" ", DateTime.Now.ToString (), Encoding.Default.GetString (bytes)); LISTBOX1.ITEMS.ADD (content);//load a message into the listbox list } Private voidWindow_Loaded (Objectsender, RoutedEventArgs e) {IP= Dns.gethostaddresses (Dns.gethostname ()) [0]. ToString (); This. Title ="from:"+ IP +"of users:"+username; } Private voidWindow_closing (Objectsender, System.ComponentModel.CancelEventArgs e) { if(Client! =NULL&&client. Connected) {client. Shutdown (Socketshutdown.both); Client. Close (); } }
:
When the service starts:
Client interface:
After clicking Send, the server displays the message:
Because the code is relatively simple, do not upload project files, here is a brief demonstration of C#socket communication core code. Readers can continue to expand on this basis.
C # Socket Programming