C # network programming

xiaoxiao2021-03-06  54

Microsoft.NET Framework provides a hierarchical, scalable and jurisded web service for your application, and its namespace system.net and system.net.socks include rich classes to develop a variety of web applications. The hierarchical structure adopted by the .NET class allows the application to access the network at different levels, developers can choose to make different levels of programming as needed, almost all incorporated all needs - from Socket sockets Ordinary request / response, more importantly, this hierarchy can be extended and can adapt to the need for Internet's continuous expansion. The 7-layer architecture of the ISO / OSI model is thrown from the logical level on the TCP / IP model. The .NET class can be considered to include 3 levels: request / response layer, application protocol layer, transport layer. WebReQEUST and WebResponse represent the request / response layer, which supports HTTP, TCP, and UDP classes that form the application protocol layer, while the Socket class is in the transport layer. Can be illustrated as follows:

It can be seen that the transport layer is located at the bottom of this structure. When the above application protocol layer and the request / response layer cannot meet the special needs of the application, it is necessary to use this layer to perform Socket socket programming. In .NET, System.Net.Sockets namespace provides a managed implementation of a Windows Sockets (Winsock) interface for developers who need to strictly control network access. All other network access classes in the System.Net Namespace are built on the socket socket implementation, such as TCPClient, TCPListener, and UDPClient class packages for more information on creating TCPs and UDP connections to the Internet; NetworkStream class provides The basic data stream of network access, etc., all of the common Internet services can see the traces of sockets, such as Telnet, HTTP, Email, Echo, etc. These services although the communication protocol protocol definition is different, its basic transmission is adopted. Socket. In fact, Socket can be considered as a data channel as a stream stream. This channel is set between the application terminal (client) and the remote server side, and the data read (reception) and write (send) are targeted This channel is carried out.

It can be seen that after the application end or the server side creates a socket object, you can use the Send / Sentto method to send data to the connected socket, or use the Receive / ReceiveFrom method to receive data from the connection socket; for the socket, .NET framework The Socket class is a managed code version of the socket service provided by the Winsock32 API. Some of them provide a large number of methods for realizing network programming, in most cases, the Socket class method is just to send data to their local WIN32 copies and handle any necessary security checks. If you are familiar with the Winsock API function, you will be very easy to write a web program with the Socket class. Of course, if you have never touched, it will not be too difficult. Follow the following explanation, you will find that using the Socket class development Windows network application originally Regulations, they follow the substantially the same steps in most cases. Before use, you need to create Socket object instance, which may be achieved by the Socket class constructor: public Socket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType); wherein, AddressFamily Socket parameter specifies the addressing scheme used, SocketType The parameter specifies the type of socket, the protocoltype parameter specifies the protocol used by the socket. The following sample statement creates a socket, which can be used to communicate on a TCP / IP network (such as the Internet). Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); to use UDP instead of the TCP, need to change the protocol type, as in the following example: Socket s = new Socket (AddressFamily.InterNetwork, SocketType .Dgram, protocoltype.udp); Once you create a socket, on the client, you will be able to connect to the specified server via the Connect method, and send data to the remote server via the send / sendto method, and then receive from the server from the server via Receive / ReceiveFrom Data; on the server side, you need to use the bind method to bind the specified interface to make the socket associated with a local endpoint and listen to the request on the interface through the Listen method. When listening to the user's connection, call Accept completes the operation of the connection, creates a new socket to process incoming connection requests. After using the socket, remember to use the shutdown method to disable the socket and use the Close method to close the Socket. The method / functions used thereto are: socket.connect method: establish a connection to remote device PUBLIC VOID Connect (Endpoint Remoteep) Socket.send method: Send data to the connection from the indication position in the data Socket. Public int send (Byte [], int, socketflags; (have an overload method) socket.sendto method sends data to a specific endpoint.

PUBLIC INT sentto (Byte [], EndPoint); (with overloaded method) Socket.Receive method: Receive data from the connected socket to a particular location of the received buffer. Public int received (Byte [], int, socketflags; socket.ReceiveFrom method: Receive data of a specific location in the data buffer and store endpoints. Public int respientFrom (Byte [], int, socketflags, ref endpoint); socket.bind method: Make Socket associated with a local endpoint: public void bind; socket.listen method: Place Socket in listening status. Public void listen; socket.accept method: Create a new Socket to process incoming connection requests. Public socket accept (); socket.shutdown method: Disable send and receive public void shutdown (socketShutdown how) on a socket; Socket.Close method: Force Socket connection to close public void close (); can be seen, many of the above methods EndPoint type parameters, in the Internet, TCP / IP uses a network address and a service port number to uniquely identify the device. Network Address Identify Specific Device on the Network; port number identifies specific services to which the device to be connected. The combination of network addresses and service ports is called endpoints, which is the endpoint class in the .NET framework, which provides information indicating the abstraction of network resources or services, to log network addresses. .NET also defines the sub-generation of EndPoint for each supported address family; for IP address family, this class is IpendPoint. The IpendPoint class contains the host and port information required for the application to connect to the service on the host, and the Host IP address and port number, the IpendPoint class form to the service connection point. When you use the IPENDPOINT class, you will inevitably involve computer IP addresses, two classes in .NET can get an IP address instance: ipaddress class: The iPadDress class contains the address on the IP network. Its PARSE method can convert an IP address string to an iPadDress instance. The following statement creates an ipaddress instance: ipaddress myip = ipaddress.parse ("192.168.1.2"); DNS class: Provide domain name services to applications that use TCP / IP Internet services. Its Resolve method queries the DNS server to map the user-friendly domain name (such as "host.contoso.com" to the digital form of Internet addresses (eg 192.168.1.1). The resolve method returns an iPhostenty instance that contains the list of addresses and aliases of the requested name. In most cases, you can use the first address returned in the AddressList array. The following code acquires an ipaddress instance that contains the IP address of the server host.contoso.com.

IPHOSTENTRY iphostinfo = dns.resolve ("host.contoso.com"); ipaddress ipaddress = iphostinfo.addresslist [0];

You can also use the gethostname method to get the iPhostry instance: iPhosnTentry Hostinfo = DNS.GETOSTBYNAME ("host.contoso.com") When using the above method, you may need to handle the following exception: Socketexception exception: Access Socket When operating the operating system Error trigger argumentnullexception: Parameter is an empty reference to trigger ObjectDisposedException exception: Socket has been turned off After mastering the knowledge, the following code will be the server host (Host.Contoso.com with port number to create remote Endpoint: IpendPoint IPE = New IpendPoint (iPadDress, 11000); Determines the address of the remote device and selects the port for connection, the application can attempt to establish a connection with the remote device. The following example uses an existing IpendPoint instance Connect with the remote device and capture possible exceptions: try {s.connect (IPE); // Try connection} // processing parameter is an empty reference exception Catch (argumentnullexception ae) {Console.writeLine ("argumentnullexception: {0} ", AE.TOString ());} // Handling operating system anomaly Catch (socketexception se) {console.writeline (" socketexception: {0} ", se.tostring ());} catch (Exception E) {Console. WriteLine ("Unexpected Exception: {0}", E.TOString ());} You need to know that: Socket class supports two basic modes: synchronous and asynchronous. The difference is that in synchronous mode, the execution network operation The calls of functions (such as Send and Receive have been waiting until the operation is completed, returns the control to the call. In the asynchronous mode, these calls return immediately. In addition, many times, Socket programming is different from the customer The end and the server side are implemented separately, respectively, and the client is specified to send a request to the server, and the server application handles the request. This process has been mentioned above; of course, not all Socket programming You need to write these two-end program strictly; The string in the following example statement provides a page request to the remote host: string get = "Get / http / 1.1 / r / nhost:" Server "/ r / nConnection: Close / R / N / R / N"; Once the remote host specifies that the port is accepted, it can be processed using its public service program without requiring another server-side application. Comprehensively use the knowledge of the use of Visual C # to develop Socket network program, the following program segment fully implements the web page download function.

Users only need to enter remote hostnames (DNS hostnames or IP addresses with point-separated four-part indication formats) and pre-saved local file names, and take advantage of 80 ports that specifically provide HTTP services. The remote host page is saved in the local specified file. If the save format is .htm format, you can open this page in the Internet browser. Adding a code properly, you can even implement a simple browser program.

The main source code for this feature is as follows: // "Start" button event private void button1_click (object sender, system.eventargs e) {// get pre-saved file name string filename = textBox3.Text.trim (); // Remote host string hostname = textbox1.text.trim (); // port int port = int32.parse (TextBox2.Text.trim ()); // Get host information iphostentry ipinfo = dns.gethostbyname (Hostname); // Ipaddress [] ipaddress [] ipaddr = ipinfo.addresslist; // Get IP ipaddress ip = ipaddr [0]; // Combine remote endpoint iPENDPOINT HOSTEP = New IpendPoint (IP, port); // Create a Socket instance socket socket = New socket (addressFamily.internetwork, sockettype.internet, protocoltype.tcp); try {// Try connecting socket.connect (hostep);} catch (exception se) {messagebox.show ("Connection error" se.Message, " Tip information, MessageBoxButtons.Retrycancel, MessageBoxicon.information;} // Send String SendStr = "Get / Hostname " / R / NCONNECTION: CLOSE / R / n / r / n "; // Create a BYTES byte array to convert the sending string byte [] bytessendstr = new byte [1024]; // will send a content string to convert into byte byte array bytessendstr = Encodi ng.ascii.getbytes (sendStr); Try {// Send a request socket.send (bytessendstr, bytessendstr.length, 0);} catch ("send error:" ce.SHOW ("Send Error:" CE.MESSAGE , "Tips Information, MessageBoxButtrycancel, MessageBoxicon.information);} // Declaration Receive String String RCVSTR =" "; // A declaration byte array, the length of the received data is 1024 bytes byte [] recvbytes = New Byte [1024]; // Returns the number of bytes of actual reception content INT BYTES = 0; // Recycling Read until all data while (true) {bytes = socket.Receso (Recvbytes, Recvbytes.length, 0); // After reading the completion, exit the cycle IF (Bytes <= 0) Break; // Convert the number of bytes of the read to a string RECVSTR =

Encoding.ascii.getstring (recvbytes, 0, bytes);} // convert the read string to byte array byte [] content = encoding.ascii.getBytes (RECVSTR); try {// Create a file stream object Example FileStream Fs = New FileStream (FileName, FileMode.Openorcreate, FileAccess.Readwrite); // Write Fs.Write (Content, 0, Content.length);} catch (exception fe) {messagebox.show ("file creation / Write error: " Fe.Message," Tips ", MessageBoxButtons.Retrycancel, MessageBoxicon.information;} // Disable Socket Socket.Shutdown (socketshutdown.both); // Close Socket Socket.close (); } Program in WindowsXP Chinese, .NET FrameworkD Chinese official version, Visual Studio.net Chinese official version of the debugging through C # network programming

We know one of the differences between C # and C , that is, he has no class library, the class library used is the class library in the .NET Framework SDK. Two namespaces are provided for network programming in the .NET Framework SDK: "System.Net" and "System.Net.Sockets". C # is a network communication with the classes and methods packaged in these two namespaces. First we explain the concepts often encountered during the network program: Synchronous, Asynchronous, Block and Nonclock: The so-called synchronization mode is the sender's sending data package. The next packet is then transmitted for unequal acceptance. The asynchronous mode is that after the sender sends a packet, it will then send the next packet after the acceptor response will be sent. The blocking socket refers to the network call to which this socket is executed until the call is successful, otherwise this set of hips is blocked on the network call, such as calling the StreamReader class Readlin () method read the network buffer. Data, if there is no data arrival when calling, then this readlin () method will always hang up until some data is read, and this function call returns; not blocking socket refers to this set When the word is called, no matter whether it is successful, it will return immediately. The READLIN () method of the StreamReader class is also called in the network buffer, and the data is returned if it is read or not, it will not be hanging on this function call. In Windows Network Communication Software Development, the most common method is asynchronous non-blocking socket. The method of usually said C / S (client / server) structure is asynchronous non-blocking mode. In fact, in the network programming with C #, we don't need to understand what synchronous, asynchronous, blocking, and non-blocking principles and working mechanisms, because these mechanisms have been packaged in .NET Framewrok SDK. Below we use C # to open a specific network program to illustrate the problem. One. The program design and operational environment described herein (1). Microsoft Window 2000 Server Edition (2) .. Net Framework SDK Beta 2 or above. Key Steps and Workarounds of Server-side programming: In the following programs, we use asynchronous blocking ways. (1). First, create a "TCPListener" object listening to the request on the network on a given port. An instance of a socket for processing access connection requests is generated by calling the "Acceptner" method by calling the "TCPListener" object after receiving the connection request.

Below is the specific implementation code: // Create a TCPListener object, this object is mainly listening to the giveholding port to listen to TCPListener = new TCPListener (1234); // Start listening TCPListener.Start (); // Return can be used to handle Connected Socket Instance SocketForClient = tcplistener.acceptSocket (); (2). Accept and send client data: At this point the socket instance has been generated, if there is a request on the network, after the request passes, the Socket instance constructs a "networkStream" object, "NetWorkStream" object provides basic data stream for network access. We have implemented access to the "NetWorkStream" object by encapsulated by Name Space "System.io". The Readline () method in the "StreamReader" class is to read a line of characters from the "NetworkStream" object; the WriteLine () method in the "StreamWriter" class is to write a line string in the "NetWorkStream" object.

Thus, the string is implemented on the network. The following is the specific implementation code: Try {// If the return value is "true", the generated set of jackets has accepted the connection request if (socketforclient.connected) {ListBox1. Items.add ("has been successfully connected to the client!"); While (true) {// Creating a NetworkStream object accepts and sends data networkStream = New NetworkStream (SocketforClient); // from the current data stream Read a line of characters, the return value is a string streamreader = new streamreader; string msg = streamreader.readLine (); listbox1.items.add ("Received Client Information: MSG); streamwriter = new streamwriter NetworkStream); if (textBox1.text! = ") {listbox1.items.add (" Go to Client Feedback: " TextBox1.text); // Write a string in the current data stream Streamwriter.writeLine (TextBox1.text); // Refresh the data in the current data stream in the current data stream. STREMWRITER.FLUSH ();}}}} catch (}}}} catch (}}}});} (ttostring ());} (3). Don't forget To turn it off, stop listening to the network, turn off the jacket words, specifically: // Turn off the thread and stream NetWorkStream.close (); streamReader.close (); streamwriter.close (); _thread1.abort (); tcplistener .Stop (); socketforclient.shutdown (socketshutdown.both); socketforclient.close (); three. Part of the C # Network programming server-side program: Server.cs): Since the structure we use in this program is an asynchronous blocking method, in the actual program, in order not to affect the running speed of the server-side program, we A thread is designed in the program so that the network requests listening, accepting, and sending data are handled in the thread. Please pay attention to this in the code below. Here is the full code of Server.cs: use system; use system. Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net.Sockets; using System.IO; using System.Threading; using System.Net; // importer Used Space Public Class Form1: Form {Private ListBox ListBox1; Private Button Button2; Private TEXTBOX TEXTBOX1; Private Button Button1; Private Socket SocketforClient;

private NetworkStream networkStream; private TcpListener tcpListener; private StreamWriter streamWriter; private StreamReader streamReader; private Thread _thread1; private System.ComponentModel.Container components = null; public Form1 () {InitializeComponent ();} // clear the resources used in the program protected override void Dispose (bool disposing) {if (disposing) {if (components = null!) {components.Dispose ();}} base.Dispose (disposing);} private void InitializeComponent () {label1 = new Label () Button2 = new button (); button1 = new button (); listbox1 = new listbox (); textbox1 = new textbox (); suspendlayout (); label1.location = new point (8, 168); label1.name = " Label1 "; label1.size = new size (120, 23); label1.tabindex = 3; label1.text =" Towards to client feedback: "; // Set other controls, here to THIS.CONTROLS. Add (button1); this.controls.add (TextBox1); this.controls.add (label1); this.controls.add (button2); this.controls.add (listbox1); this.maximizebox = false; this.minimizeBox = false; THIS.N AME = "Form1"; this.text = "C # network programming server side! "; this.closed = new system.eventhandler (this.form1_closed); this.ResumeLayout (false);} private void listen () {// creates a TCPListener object, this object is mainly to listen to TCPListener for a given port = New TCPLISTENER (1234); // Start listening tcplistener.Start (); // Returns Socket instance socketforClient = tcplistener.acceptsocket () can be used to handle the connection, if the return value is "true", then The generated set words have accepted the connection request if (socketforclient.connected) {listbox1.Items.add ("has been successfully connected to the client!"); While (true) {// Create a NetworkStream object via the web set The word accepts and sends the data networkStream = New NetworkStream (socketforClient); / / reads a line from the current data stream,

The return value is a string streamReader = new StreamReader (networkStream); string msg = streamReader.ReadLine (); ListBox1.Items.Add ( "Client message received:" msg); streamWriter = new StreamWriter (networkStream); if ( TextBox1.text! = "" "{listbox1.items.add (" Go to Client Feedback Information: " TextBox1.text); // Write a line of string in the current data stream streamwriter.writeline (TextBox1.text) // Refresh the data streamwriter.flush ();}}}} catch (}}}});}} static void main ()}}}}}};}}}}}};}}}}}}; Form1 ());} private void button1_click (Object sender, system.eventargs e) {listbox1.items .add ("Service has started!"); _Thread1 = new thread (New Threadstart (Listen)); _thread1.Start () } private void button2_click (object sender, system.eventargs e) {// Close thread and stream networkStream.close (); streamReader.close (); streamwriter.close (); _thread1.abort (); tcplistener.Stop () SocketforClient.shutdown (socketshutdown.both); socketforclient.close ();} private void form1_closed (Object sender, system.eventargs e) {// close Threads and flow networkStream.Close (); streamReader.Close (); streamWriter.Close (); _thread1.Abort (); tcpListener.Stop (); socketForClient.Shutdown (SocketShutdown.Both); socketForClient.Close ();}} four. Key Steps and Solutions for Client Programming: (1). Connect to the specified port of the server: The local machine we use both both the server and the client, you can confirm the IP address to determine the server you want to connect. We use the "TCPClient" class when connecting, which provides TCP services on a higher abstraction level (higher than the socket class).

The following code is to connect to the local machine (port 1234) and get the response stream: // Connect to the server port, here is the selected local machine as the server, you can change the server Try {myclient = new TCPClient by modifying the IP address. "LocalHost", 1234);} catch {messagebox.show ("Not connected to Server!"); Return;} // Creating a NetworkStream object Accepts and sends data NetWorkStream = myclient.getStream (); streamReader = New StreamReader; streamwriter = new streamwriter; (2). Implementation and sending data: In accepting and sending data, we still use the "NetWorkStream" class, because it is relatively simple to operate, specifically Implementation and acceptance or WriteLine () method of the "StreamWriter" class () method and "streamwriter" class in the "system.io" of the namespace. The specific implementation method is as follows: if (textBox1.text == ") {messagebox.show (" Please make sure the text box is not empty! "); TextBox1.focus (); return;} try {string s; // The current data stream is written to a string streamWriter.writeline (TextBox1.text); // Refresh the data streamwriter.flush () in the current data stream; // read a line from the current data stream, return value is character String s = streamreader.readline (); listbox1.items.add ("Read server-side sending content:" s);} catch (Exception EE) {MessageBox.show ("from server-side read data error, type To: " EE.TOSTRING ());} (3). The last step is the same as the server side, that is, to close the stream created in the program, as follows: streamReader.close (); streamwriter.close (); networkStream .Close (); 5. Partial code of the client: Since there is no listening network on the client, there is no program blocking situation above, in the following code, we did not use the thread, which is a difference between the server-side program.

Summarize these key steps, you can get a client program (Client.cs) programming with C # network, which is as follows: use system; using system.drawing; use system.collections; using system.componentmodel; use system.Componentmodel; Windows.Forms; using System.Data; using System.Net.Sockets; using System.IO; using System.Threading; // used in the program to import namespace public class Form1: Form {private ListBox ListBox1; private Label label1; private TextBox textBox1; private Button button3; private NetworkStream networkStream; private StreamReader streamReader; private streamWriter streamWriter; TcpClient myclient; private Label label2; private System.ComponentModel.Container components = null; public Form1 () {InitializeComponent ();} // Clear Various resources used in the program protected {if (disponents! = Null) {components.dispose ();}}}} {Label1 = new label (); button3 = new button (); listbox1 = new listbox (); textBox1 = new textbox (); label2 = new label (); suspendlayout (); label 1.Location = New Point (8, 168); label1.name = "label1"; label1.size = new size (56, 23); label1.tabindex = 3; label1.text = information: "; // Method Set other control autoscalebasesize = new size (6, 14); clientsize = new size (424, 205); this.controls.add (button3); this.controls.add (TextBox1); this.Controls.add (label1) im.controls.add (label2); this.controls.add (listbox1); this.maximizebox = false; this.minimizebox = false; this.name = "form1"; this.text = "C # network programming customers Device! "; this.closed = new system.eventhandler (this.form1_closed); this.ResumeLayout (false);

// Connect to the server port, here is the use of local machines as the server, you can change the server with the IP address to change the server try {myclient = new TcpClient ("localhost", 1234);} catch {messagebox.show ("not connected to server ");! return;} // Create NetworkStream objects through a network to receive and transmit data bytes sleeve networkStream = myclient.GetStream (); streamReader = new StreamReader (networkStream); streamWriter = new streamWriter (networkStream);} static void Main () {Application.Run (New Form1 ());} private void button3_click (object sender, system.eventargs e) {if (textbox1.text == ") {messagebox.show (" Please make sure the text box is not Empty! "); TextBox1.focus (); return;} trying s; // Write a line string streamwriter.writerine (TextBox1.text) in the current data stream; // Refresh the data in the current data stream Streetwriter.flush (); // reads a line from the current data stream, the return value is a string S = streamreader.readLine (); listbox1.items.add ("Read the server side Send content: s); } catch (Exception EE) {MessageBox.show ("From the server-side read data error, the type is:" EE.TOSTRING ());}}}}}}}}}}}}} void form1_closed (Object Sender, System.EventArgs E) {streamReader. CLOSE (); streamwriter.close (); networkStream.close ();}} Network communication based on TCP protocol with C #

The TCP protocol is a basic network protocol. Basically all network services are based on TCP protocols such as http, ftp, etc., so you have to understand network programming, you must understand the programming based on TCP protocol. However, the TCP protocol is a parent-shaped system, and it is necessary to clear its implementation. It is not a day and two days. Fortunately, in the .NET Framework environment, we don't have to investigate the implementation of the TCP protocol, which can be very convenient. Write procedures based on TCP protocols. To make a TCP-based network communication, you must first establish a connection with the remote host. The connection address usually includes two parts - host names and ports, such as www.yesky.com: 80, www.yesky.com is the host name 80 refers to the 80 port of the host, of course, the host name can also be replaced with an IP address. When the connection is established, you can use this connection to send and receive the data packet. The role of the TCP protocol is to ensure that these packets can reach the end point and can be assembled in the correct order. In the Class Library of .NET Framework, two classes for TCP network communication are provided, named TCPClient and TCPListener, respectively. It is obvious from its English meaning, and the TCPCLIENT class is a client class based on the TCP protocol, and TCPListener is a connection request from the server side, listening (Listen) client. The TCPCLIENT class communicates with the server through the TCP protocol, which encapsulates an instance of a Socket class internally, which is used to request and obtain data to the server using the TCP protocol. Since interaction with the remote host is in the form of a data stream, the transmitted data can be read and written using the .NET Framework. In the example below, you can see how the data streams using the NetworkStream class. In the following example, we will establish a time server, including server-side programs, and client programs. The server is listened to the client's connection request and establishes a connection to send the current system time to the client.

  First run the server-side program, the screenshot below shows the status of the server-side program: Run the client program, the client first sends a connection request to the server side, and the server is sent to send the current time to the client, this is Screenshot of the client program: After the send is complete, the server continues to wait for the next connection:   Through this example we can learn the basic usage of the TCPClient class, you must use this class, you must use the system.net.socket namespace, this The three namespaces used are as follows:                                                                             First discuss the client program, start we must initialize an instance of a TCPClient class: TcpClient Client = New TcpClient (Hostname, Portnum); then use the TCPClient class GetStream () method to get the data stream, and initialize it with it An instance of a NetWorkStream class:   NETWorkStream ns = client.getStream (); Note that when using the host name and port number to initialize the TCPClient class instance, this instance is only established, the program can be true. Down execution. If the network is not available, the server does not exist, the server port is not open, and the server cannot be connected, the program will throw an exception and interrupt execution. After establishing a stream, we can read data from the stream using the READ () method of the NetworkStream class, using the Write () method to write data to the stream. When reading data, you should first create a buffer, specifically, it is to create an array of BYTE types to store data read from the stream. Prototype Description Read () method is as follows: public override int Read (in byte [] buffer, int offset, int size) buffer a buffer array, offset data (byte stream) stored in the buffer array to begin Location, size is the number of bytes read, and the return value is the number of bytes read.

In this example, the method is simply used to read the information of the server feedback:                                                                                                                                           \ .Length); // Read byte streaming then displayed on the screen: Console.writeline (Encoding.ascii.getstring); Last Don't forget to turn off the connection:   The following is the complete program list of this example:                                                                                                                      TCPTIMECLIENT {{Private const portnum = 13; // server port, can be invited to modify, Private const String hostname = "127.0.0.1"; // server address, 127.0 .0.1 Refers to this machine [STATHREAD]                                                                                                                    Console.Write ("try to connect to" hostname ":" portnum.tostring () "/ r / n");                                                   @ p TcpClient Client = New TcpClient (Hostname, Portnum); NETWORKSTREAM NS = Client.getStream ();                                                                                 circonsole.writel àcoding.ascii.getstring (bytes, 0, bytesread) ;client.close () ;console.readline (); // Because it is a console program, it can be added to this sentence. Console.writeline (E.tot). Clearly demonstrate the key points of the client program, let's discuss how to establish a server program. This example will use the TCPListener class, listen on the 13th port, once a client connection is available, will immediately send the current server time information to the client. The key toTCPListener is an AcceptTCPClient () method that detects the unopened connection request if there is an untreated connection request, which will make the server to establish a connection with the client, and return a TCPCLIENT object, pass through The GetStream method of this object establishes the data stream with the client communication.

In fact, the TCPListener class also provides a more flexible approach acceptsocket (), of course, flexible cost is complicated, and AccepttcpClient () is already enough for relatively simple programs. In addition, the TCPListener class provides the start () method to start listening, providing the STOP () method to stop listening.

First we use port to initialize a TCPListener instance and start listening at 13 ports: Private const Int portnum = 13 ;TCPListener Listener = New Tcplistener (portnum) ;Listener.Start (); // Start listening If there is an unprocessed connection request, use the AccepttcpClient method to process and get the data stream: TcpClient client = listener.accepttcpclient () ;NetworkStream ns = client.getStream (); then, get the unit Time, and save in the byte array, use the networkStream.write () method to write to the data stream, and the client can get this information from the data stream via the read () method:                                 ASCII.GetBytes (DateTime.Now.ToString ()); ns.Write (byteTime, 0, byteTime.Length); ns.Close (); // Do not forget to close the connection and data stream client.Close (); Server-side program full program list is as follows:                                                                                                                               {                                                                                                                                                                                                                 wt (! DONE)            CONSOLE.WRITE ("Waiting for Connection ..."); TcpClient Client = listener.accepttcpclient ();            -                                                                                                   Ascii.getbytes (DateTime.now.tostring ());                             (ByTetime, 0, bytetime.Length);                                                                                                                                                                                                        Console.Writeline .Tostring ());

转载请注明原文地址:https://www.9cbs.com/read-117092.html

New Post(0)