C#网络编程.2.套接字.TcpListener.TcpClient.服务端客户端通信

本文详细介绍了服务器端如何使用TCP协议监听并接受客户端连接,通过`GetStream()`方法获取连接至客户端的流,并从流中读取数据进行处理。同时,展示了客户端如何通过`Connect()`方法建立与服务器的连接,利用`Write()`方法向服务器发送数据。讨论了在处理大对象如图片或文件时的注意事项,以及分次读取和转存的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

服务器端

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(); 
        } 
    } 
} 


image

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值