流服务器 using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace StreamTcpSrvr ... { class Program ...{ static void Main(string[] args) ...{ string data; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); NetworkStream ns = new NetworkStream(client); StreamReader sr= new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); string welcome = "Welcome to my test server"; sw.WriteLine(welcome); sw.Flush(); while (true) ...{ try ...{ data = sr.ReadLine(); } catch (IOException) ...{ break; } Console.WriteLine(data); sw.WriteLine(data); sw.Flush(); } Console.WriteLine("Disconnected from {0}", newclient.Address); sw.Close(); sr.Close(); ns.Close(); } }} 流客户机 using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace StreamTcpClient ... { class Program ...{ static void Main(string[] args) ...{ string data; string input; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try ...{ server.Connect(ipep); } catch (SocketException e) ...{ Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } NetworkStream ns = new NetworkStream(server); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); data = sr.ReadLine(); Console.WriteLine(data); while (true) ...{ input = Console.ReadLine(); if (input == "exit") break; sw.WriteLine(input); sw.Flush(); data = sr.ReadLine(); Console.WriteLine(data); } Console.WriteLine("Disconnecting from server..."); sr.Close(); sw.Close(); ns.Close(); server.Shutdown(SocketShutdown.Both); server.Close(); } }}