.net 实现TCP通讯中:客户端软件指定本地端口号,实时接收服务端的数据
时间: 2024-03-10 17:44:40 浏览: 29
在 .NET 实现 TCP 通讯中,客户端软件可以指定本地端口号,并实时接收服务端的数据。以下是一段示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// 指定本地 IP 地址和端口号
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
// 创建 TCP 客户端套接字并绑定本地端口号
TcpClient client = new TcpClient();
client.Client.Bind(localEndPoint);
// 连接到服务端
client.Connect("127.0.0.1", 1234);
// 接收服务端的数据
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string data = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("接收到数据:{0}", data);
}
// 关闭套接字和流
stream.Close();
client.Close();
}
}
```
在上述代码中,首先创建了一个 IPEndPoint 对象 localEndPoint,该对象包含了本地 IP 地址和端口号。接下来创建了一个 TcpClient 对象,并调用了 client.Client.Bind 方法将 TCP 客户端套接字绑定到指定的本地 IP 地址和端口号。然后调用了 client.Connect 方法,连接到服务端的 IP 地址和端口号。
接下来通过调用 TcpClient 对象的 GetStream 方法获取 NetworkStream 对象,然后循环调用 NetworkStream 对象的 Read 方法,实时接收服务端的数据。将接收到的数据转换为字符串,并打印输出。最后关闭 NetworkStream 和 TcpClient 对象。
这样就可以在 .NET 实现 TCP 通讯中指定本地端口号,并实时接收服务端的数据了。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)