C # network programming (synchronous transmission of strings) 2

Source: Internet
Author: User
Tags getstream

Server Client Communication

After establishing a connection with the server, we can use this connection to send and receive data. Data is transmitted between a port and a port in the form of a Stream. Because almost any object can be saved to a Stream, data of any type can be transmitted between the client and the server. For the client, writing data to the stream means transmitting data to the server; reading data from the stream means receiving data from the server. For the server, writing data to the stream means sending data to the client; reading data from the stream means receiving data from the client.

Synchronous Transmission string

Now we want to consider a task: the client prints a string and sends it to the server. The server first outputs it, converts it to uppercase, and then sends it back to the client. After the client receives it, print it again. We divide it into two parts: 1. Sending by the client, receiving and outputting by the server, and 2. Sending by the server, receiving and outputting by the client.

1. The client sends messages. The server receives and outputs 1.1 server programs.

We can call the GetStream () method on TcpClient to obtain the stream connected to the remote computer. Note that I have usedRemoteWhen called on the client, it gets the stream connected to the server; when called on the server, it gets the stream connected to the client. Next let's take a look at the code. Let's first look at the server (Note that do/while loops are not used here):

Class Server {
Static void Main (string [] args ){
Const int BufferSize = 8192; // cache size, 8192 bytes

Console. WriteLine ("Server is running ...");
IPAddress ip = new IPAddress (new byte [] {127, 0, 0, 1 });
TcpListener listener = new TcpListener (ip, 8500 );

Listener. Start (); // Start listening
Console. WriteLine ("Start Listening ...");

// Gets a connection and interrupts the connection.
TcpClient remoteClient = listener. AcceptTcpClient ();
// Print the information of the connected Client
Console. WriteLine ("Client Connected! {0} <-- {1 }",
RemoteClient. Client. LocalEndPoint, remoteClient. Client. RemoteEndPoint );

// Obtain the stream and write it into the buffer.
NetworkStream streamToClient = remoteClient. GetStream ();
Byte [] buffer = new byte [BufferSize];
Int bytesRead = streamToClient. Read (buffer, 0, BufferSize );
Console. WriteLine (" Reading data, {0} bytes... ", bytesRead );

// Obtain the request string
String msg = Encoding. Unicode. GetString (buffer, 0, bytesRead );
Console. WriteLine ("Received: {0}", msg );

// Exit by Q
}
}

The first half of this program is familiar, so I will not explain it any more. RemoteClient. the GetStream () method obtains the stream connected to the client, reads data from the stream, stores the data in the buffer cache, and then uses Encoding. unicode. the GetString () method obtains the actual string from the cache. Finally, print the string on the console. Note: When the total number of bytes of a string that can be read is greater than BufferSize, string truncation occurs because the number of cached files is always limited. For large objects, for example, for images or other files, you must use the "read multiple times and then store them" method, for example:

// Obtain the string
Byte [] buffer = new byte [BufferSize];
Int bytesRead; // number of bytes read
MemoryStream msStream = new MemoryStream ();
Do {
BytesRead = streamToClient. Read (buffer, 0, BufferSize );
MsStream. Write (buffer, 0, bytesRead );
} While (bytesRead> 0 );

Buffer = msStream. GetBuffer ();
String msg = Encoding. Unicode. GetString (buffer );

I didn't use this method here. One is because I don't want to focus too much on the details. The other is because there are already many 8192 bytes for strings, and we usually won't pass so much text. When Unicode encoding is used, 8192 bytes can store 4096 Chinese and English characters. The number of bytes occupied by different encoding methods varies greatly. At the end of this article, there is a small program, it can be used to test the number of bytes occupied by Unicode, UTF8, and ASCII encoding methods for string encoding.

Now, the client is not modified, and then the server is run first, and then the client is run. The result is that the server prints "Client Connected!" again! After 127.0.0.1: 8500 <-- 127.0.0.1: xxxxx ", it is blocked again and" Reading data, {0} bytes... "is not output ...". Visible,Similar to the AcceptTcpClient () method, the Read () method is also synchronous. The server reads data and runs this method only when the client sends data, otherwise, it will wait.

1.2 client program

Next, we write the code that the client sends to the server. Similar to the server, it first obtains the stream connecting to the server, saves the string to the buffer cache, and then writes the cache to the stream, the process of writing a stream is equivalent to sending a message to the server.

Class Client {
Static void Main (string [] args ){
Console. WriteLine ("Client Running ...");
& N

Related Article

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.