(2) Socket Network programming (C #)----Synchronous transfer of strings

Source: Internet
Author: User
Tags array to string getstream

The ◇networkstream class specializes in providing the underlying data flow for network access. He implements the standard. NET Framework streaming mechanism for sending and receiving data over a network socket. Supports synchronous and asynchronous access to network data streams.

In the ◇.net framework, the NetworkStream stream supports two operations.

◇1) write to the stream, the main use of the method is write (), write from the data structure to the flow of data transmission, the data is written to NetworkStream.

◇2) Read the stream, the main use of the method is read (), read from the stream to the data structure of the data transfer, but also read from the Networkstram data.

    ◇3) Note that the data that is received and sent is best done through a byte array, since almost all objects can be saved to the inflow.

The ◇networkstream object can be returned from the GetStream () method of the TcpClient object, for example:

NetworkStream streamtoserver = client. GetStream ();

◇ Note: Both the client program and the server program require a NetworkStream object to receive or send the data stream. Where the TcpClient object of the client program can be instantiated directly, and the server's TcpClient object is returned through the TcpListener object's AcceptTcpClient () method, the code is as follows:

TcpClient client = listener. AcceptTcpClient ();      // client objects on the server side New TcpClient ();                    // Client Objects for clients

◇ Now we write two programs, one program is server side, the other program is client.

◇1) Server Segment program implementation function: Listen to a port, receive and print out the received data, and then turn this data into uppercase, sent back. (The note has been written very clearly)

1 class Program2     {3         Static voidMain (string[] args)4         {5IPAddress IP =NewIPAddress (New byte[] {127,0,0,1});//Set IP6TcpListener listener =NewTcpListener (IP,8500);//Create a Listener object7 8Listener. Start ();//Start listening .9 TenTcpClient client = listener. AcceptTcpClient ();//establish a connection with the client One  AConsole.WriteLine ("connection succeeded, {0}+++++{1}", client. Client.localendpoint,client. Client.remoteendpoint);//Print out connection information -  -  the             byte[] buffer =New byte[8192]; -NetworkStream stream = client. GetStream ();//Create a NetworkStream object using the GetStream () method -             intnumb = stream. Read (Buffer,0,8192);//use the Read () method to write the received data to a byte array -  +             strings = Encoding.Unicode.GetString (buffer,0, numb);//converts data in a byte array to string type using the GetString method of the encoding -Console.WriteLine ("{0}", s);//output to the screen +s = S.toupper ();//Convert to uppercase ABuffer = Encoding.Unicode.GetBytes (s);//use Encoding's GetString method to re-convert string strings into byte arrays atStream. Write (Buffer,0, buffer. Length);//transfer data back to the client through the Write method - Console.WriteLine (s); - Console.readkey (); -         } -}

◇ Note that this is a synchronous way of implementation.

  

◇ to write a corresponding client program: To connect the above server port, send data to the port, and accept the data from the above server and print, is also a synchronous way, the specific code is as follows:

1 class Program2     {3         Static voidMain (string[] args)4         {5Console.WriteLine ("Client Running ...");6 TcpClient client;7 8             Try9             {TenClient =NewTcpClient (); OneClient. Connect ("localhost",8500);//Connect to Server A             } -             Catch(Exception ex) -             { the Console.WriteLine (ex. Message); -                 return; -             } -             //Print the service-side information connected to +Console.WriteLine ("Server connected! {0}--and {1}", - client. Client.localendpoint, client. Client.remoteendpoint); +  A             stringmsg ="\ "Welcome to Tracefact.net\""; atNetworkStream streamtoserver = client. GetStream ();//Create a client-side NetworkStream object -  -             byte[] buffer = Encoding.Unicode.GetBytes (msg);//Get Cache -Streamtoserver.write (Buffer,0, buffer. Length);//Send to Server -Console.WriteLine ("Sent: {0}", msg); -  in             intnumb = streamtoserver.read (buffer,0, buffer. Length);//receive data from the server and save it to the buffer array (byte type) -             strings = Encoding.Unicode.GetString (buffer,0, buffer. Length);//Converts the contents of an array into string strings, and outputs to Console.WriteLine (s); + Consolekey key; -  the              Do        //blocking the program for viewing results *             { $Key = Console.readkey (true). Key;Panax Notoginseng} while(Key! =consolekey.q); -  the  + console.readline (); A         } the}

  ◇ Two programs are console programs, written in different solutions, two programs written well, first run the server program, and then run the client program, you can clearly see the results.

(2) Socket Network programming (C #)----Synchronous transfer of strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.