Zep*_*hni 3 c# tcp client-server tcpclient
我一直在遵循本教程“ http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server ”设置可发送和接收消息并连接多个客户端的小型服务器。
一切正常,这很好。.但是不幸的是,本教程中缺少的一件事是客户端如何设置侦听器以侦听服务器。
我只有这么多:
public void SetupReceiver()
{
TcpClient tcpClient = new TcpClient(this.Host, this.Port);
NetworkStream networkStream = tcpClient.GetStream();
// What next! :( or is this already wrong...
}
Run Code Online (Sandbox Code Playgroud)
据我所能想象的..我需要连接到服务器(作为TcpClient)并获取流(如上)。然后等待消息并对其进行处理。发送邮件后,我不能让客户端立即从服务器收到消息的原因是,客户端将向服务器发送消息,然后该消息将广播到所有连接的客户端。因此,每个客户端都需要“侦听”来自服务器的消息。
该TcpClient的类拥有必要的资源,使一个连接,发送和接收数据,并从服务器和的TCPListener类本质上是服务器。
遵循msdn页面中为TCPclient提供的一般示例,并且也可以将其用于TCPListener(我的概括解释基于此!)
https://msdn.microsoft.com/zh-CN/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx
第一部分是将数据发送到服务器:
// 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**)
Run Code Online (Sandbox Code Playgroud)
以下部分是从服务器接收数据:
// 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**)
Run Code Online (Sandbox Code Playgroud)
一旦将字节方法链接到网络流,就可以用流读取器和流写入器替换它们
希望这可以帮助!!
** PS:如果您想在c#中使用网络类提供更通用的编码经验,我个人建议您研究使用套接字,因为它是tcpclient和tcplistener诞生的主要类。
| 归档时间: |
|
| 查看次数: |
15478 次 |
| 最近记录: |