在TcpClient上调用GetStream()方法来获得连接到远程计算机的流。注意这里我用了远程这个词,当在客户端调用时,它得到连接服务端的流;当在服务端调用时,它获得连接客户端的流。接下来我们来看一下代码,我们先看服务端
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace SocksTest { class Program { static void Main(string[] args) { int BufferSize=1000; Console.WriteLine("Server is running ... "); IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 }); TcpListener listener = new TcpListener(ip, 8500); listener.Start(); // 开始侦听 Console.WriteLine("Start Listening ..."); TcpClient remoteClient = listener.AcceptTcpClient();//接受挂起的连接请求 Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint.ToString(), remoteClient.Client.RemoteEndPoint.ToString()); NetworkStream streamClient = remoteClient.GetStream(); Byte[] buffer=new Byte[BufferSize]; int bytesRead = streamClient.Read(buffer, 0, BufferSize); Console.WriteLine("Reading data,{0} bytes...",bytesRead); string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received:{0}",msg); Console.Read(); } } }
streamClient.GetStream()方法获取到了连接至客户端的流,然后从流中读出数据并保存在了buffer缓存中,随后使用Encoding.Unicode.GetString()方法,从缓存中获取到了实际的字符串。最后将字符串打印在了控制台上。这段代码有个地方需要注意:在能够读取的字符串的总字节数大于BufferSize的时候会出现字符串截断现象,因为缓存中的数目总是有限的,而对于大对象,比如说图片或者其它文件来说,则必须采用“分次读取然后转存”这种方式
// 获取字符串 byte[] buffer = new byte[BufferSize]; int bytesRead; // 读取的字节数 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);
客户端
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; namespace SocksClient { class Program { static void Main(string[] args) { Console.WriteLine("Client is running......"); TcpClient tcpClient; try { tcpClient = new TcpClient(); tcpClient.Connect("localhost", 8500); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Read(); return; } Console.WriteLine("Server Connected!{0} --> {1}", tcpClient.Client.LocalEndPoint.ToString(), tcpClient.Client.RemoteEndPoint.ToString()); NetworkStream streamServer = tcpClient.GetStream(); string msg = "Hi server,this is from Client"; byte[] buffer=Encoding.Unicode.GetBytes(msg); streamServer.Write(buffer, 0, buffer.Length); Console.Read(); } } }
同样的,和上篇的原理相同,如何实现多客户端与服务器通信等等,我这里抛个砖,接下来由大家自己继续深入了。
1. 单C<--->单S 通信
2. 多C<--->单S 通信
3. 单C多信息<--->单S 通信
4. 多C多信息<--->单S 通信