TCPclient 类具有必要的资源来启用与服务器的连接,发送和接收数据, TCPListener 类本质上是服务器 .
遵循msdn页面中为 TCPclient 提供的一般示例,也可以用于 TCPListener (我的通用解释基于!)
第一部分是将数据发送到服务器:
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length); //(**This is to send data using the byte method**)
以下部分是从服务器接收数据:
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length); //(**This receives the data using the byte method**)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); //(**This converts it to string**)
字节方法一旦链接到 networkstream 就可以用 streamreader 和 streamwriter 替换
希望这可以帮助!!
** PS:如果您希望在c#中使用网络类具有更多功能的编码体验,我个人建议使用套接字,因为它是tcpclient和tcplistener诞生的主要类 .