1、服务器端程序
可以在TcpClient上调用GetStream()方法来获的链接到远程计算机的网络流NetworkStream。当在客户端调用时,他获的链接服务器端的流;当在服务器端调用时,他获得链接客户端的流。
class Program { static void Main(string[] args) { const int BufferSize = 8192;//缓存大小 Console.WriteLine("server is running ..."); IPAddress ip = new IPAddress(new byte[] { 192, 168, 1, 102 });//IP TcpListener listener = new TcpListener(ip, 8500); listener.Start();//开始侦听 Console.WriteLine("start listener ..."); //获取一个链接中断方法 TcpClient remoteclient = listener.AcceptTcpClient(); //打印链接到客户端的信息 Console.WriteLine("client connected ! Local:{0}<-- Client:{1}", remoteclient.Client.LocalEndPoint, remoteclient.Client.RemoteEndPoint); //获取流,并写入Buffer中 NetworkStream streamToClient = remoteclient.GetStream(); byte[] buffer = new byte[BufferSize]; int bytesRead = streamToClient.Read(buffer, 0, BufferSize); //获得请求字符串 string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received:{0}[{1}bytes]", msg, bytesRead); Console.WriteLine("\n\n输入\"Q\"键退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } }
如果传递的数据字节比较大,如图片、音频等,则采用“分次读取然后转存”的方式,代码如下:
//获取字符串 byte [] buffer = new byte[BufferSize]; int bytesRead; //读取的字节数 MemoryStream ms =new MemoryStream(); do{ bytesRead = streamToClient.Read(buffer,0,BufferSize); ms.Write(buffer,0,bytesRead); }while(bytesRead > 0); buffer = msStream.GetBuffer(); string msg = Encoding.Unicode.GetString(buffer);
2、客户端程序
客户端向服务器发送字符串的代码与服务器端类似,先获取链接服务器端的流,将字符串保存到buffer缓存中,再写入流,写入流的过程就相当于将消息发送到服务器端。
class Program { static void Main(string[] args) { Console.WriteLine("client is running ..."); TcpClient clint; try { clint = new TcpClient(); //与服务器建立连接 clint.Connect(IPAddress.Parse("192.168.1.102"), 8500); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } //打印连接到服务器端的信息 Console.WriteLine("client connected ! Local:{0}<-- Client:{1}", clint.Client.LocalEndPoint, clint.Client.RemoteEndPoint); //要发送的信息 string msg = "hello"; NetworkStream streamToServer = clint.GetStream(); //获取缓存 byte[] buffer = Encoding.Unicode.GetBytes(msg); //发送 streamToServer.Write(buffer, 0, buffer.Length); Console.WriteLine("Sent:{0}", msg); Console.WriteLine("\n\n输入\"Q\"键退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } }
这样就可以成功的发送和接收一个字符串了,如果想完成一些复杂的不间断的交互就需要自己做一些调整了。
TCP 同步传输:客户端发送,服务器段接收,布布扣,bubuko.com
时间: 2024-11-05 12:22:46