Server-Side client communication
After the connection to the server is established, we can send and receive data through this connection. Ports and ports transmit data in streams, because almost any object can be saved to the stream, so you can actually transfer any type of data between the client and the server. To the client, the data is written to the stream, the data is sent to the server, the data is read from the stream, and the data is received from the service side. For the server, the data is written to the stream, that is, the data is sent to the client, the data is read from the stream, and the data is received from the client.
Synchronizing Transmission strings
We now consider a task: the client prints a string of strings, then sent to the server, the server to output it first, and then to uppercase, and then back to the client, the client received later, and finally print it again. We will divide it into two parts: 1, the client sends, the service side receives and outputs, 2, the service end postback, the client receives and outputs.
1. The client sends, the service side receives and outputs
1.1 Server-side programs
We can use the GetStream () method on TcpClient to get a stream connecting to a remote computer. Notice that I used the word remote here, and when invoked on the client, it gets the stream that connects the server, and when invoked on the server, it gets the stream that connects the client. Let's take a look at the code, and we'll see the service side first (note that the Do/while loop is 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 ...");
Get a connection, break method
TcpClient remoteclient = listener. AcceptTcpClient ();
Print the client information that is connected to
Console.WriteLine ("Client connected! {0} <--{1} ',
RemoteClient.Client.LocalEndPoint, RemoteClient.Client.RemoteEndPoint);
Gets the stream and writes 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);
Get the requested string
String msg = Encoding.Unicode.GetString (buffer, 0, bytesread);
Console.WriteLine ("Received: {0}", msg);
Press Q to exit
}
}