C # study notes 7 (Network IO, Asynchonouse Network IO)

zhaozj2021-02-16  48

Network IO; // Server1 programm using System.Net.Sockets; TcpListener tcpListener = new TcpListener (65000); tcpListener.Start (); for (;;) {Socket clientSocket = tcpListener.AcceptSocket () if (clientSocket.Connected) { StreamFile (clientSocket); clientSocket.Close (); break;}} void StreamFile (Socket clientSocket) {NetworkStream networkStream = new NetworkStream (clientSocket); System.IO.StreamWriter streamWriter = new System.IO.StreamWriter (networkStream); System. IO.StreamReader streamReader = new System.IO.StreamReader (@ "C: /a.txt"); string strStream; do {strStream = streamReader.ReadLine (); if (strStream = null!) {streamWriter.WriteLine (strStream) ; streamWriter.Flush ();}} while (strStream = null!); streamReader.Close (); networkStream.Close (); streamWriter.Close ();} // Client1 Code using System.Net.Sockets; TcpClient serverSocket; Try {serversocket = new TcpClient ("LocalHost", 65000);} catch () {} networkStream networkStream = severSocket.GetStream (); System.IO.StreamReader streamReader = new System.IO.StreamReader (networkStream); try {string strOut; do {if (strOut = null!) {streamReader.ReadLine (strOut); if (strOut =! NULL) {Console.WriteLine (strout);}}} while (strout! = null);} catch () {}

Aysnch Network IO: // Server2 ... TcpListener = tcpListener = new TcpListener (65000); tcpListener.Start (); for (;;) {Socket socketForClient = tcpListener.AcceptSock (); if (SocketForClient.Connected) {ClientHandler handler = new ClientHandler (socketForClient); handler.StartRead ();}} class ClientHandler {private byte [] buff; private Socket socket; private NetworkStream networkSteam; private AsyncCallback cbRead; private AsyncCallback cbWrite; public ClientHandler (Socket socketForClient) {socket = socketForClient ; buff = new byte [256]; networkStream = new NetworkStream (socketForClient); cbRead = new AsyncCallback (this.OnReadComplete); cbWrite = new AsyncCallback (this.OnWriteComplete);} public void StartRead () {networkStream.BeginRead (buff, 0, buff.length, cbread, null;} private void onreadcomplete (IASYNCRESULT AR) {INTETESREAD = NetWorkStream.EndRead (ar); if (buTesRead> 0) {string s = system.text.Encodi Ng.ascii.getstring (buff, 0 Buytesread); console.write ("received {0} bytes from client: {1}, bytesread, s); networkStream.BeginWrite (buff, 0, bytesread, cbwrite, null);} else {Console.WriteLine ( "Read connection dropped"); networkStream.Close (); socket.Close (); networkStream = null; socket = null;}} // OnReadComplete private void OnWriteComplete (IAsyncResult ar) {networkStream.EndWrite ( ar) Console.WriteLine ( "Write complete"); networkStream.BeginRead (buff, 0, buff.Length, cbRead, null);} // OnWriteComplete} // Client2 Code Network NetworkStream streamToServer; TcpClient tcpSocket =

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

New Post(0)