网络通信(18)-C#TcpClient 和 TcpListener的使用实例

本文演示C#TcpClient 和 TcpListener的使用实例,掌握基本用法。

目录

TcpListener服务器

客户端TcpClient


TcpListener服务器

界面

UI代码

namespace TcpListenerDemo
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C#中的TcpClientTcpListener是用于创建和处理TCP连接的类。TcpClient用于创建TCP客户端,而TcpListener用于创建TCP服务器。 TcpClient类用于在客户端与服务器之间建立连接。可以通过TcpClient对象的构造函数创建实例,并使用Connect方法连接到指定的服务器和端口。一旦连接建立,就可以使用NetworkStream来发送和接收数据。 以下是一个简单的示例代码,演示了如何使用TcpClient发送数据: ```csharp using System; using System.Net.Sockets; class Program { static void Main() { try { TcpClient client = new TcpClient("127.0.0.1", 8080); NetworkStream stream = client.GetStream(); string message = "Hello, Server!"; byte[] data = System.Text.Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine("Message sent to the server."); stream.Close(); client.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } ``` TcpListener类用于创建TCP服务器,它监听指定的端口,并等待客户端的连接请求。可以使用AcceptTcpClient方法来接受客户端连接,并返回一个TcpClient对象以进行数据传输。 以下是一个简单的示例代码,演示了如何使用TcpListener接收数据: ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { TcpListener server = null; try { // 设置监听IP和端口 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 8080; server = new TcpListener(ipAddress, port); // 开始监听 server.Start(); Console.WriteLine("Server started. Waiting for clients..."); // 接受客户端连接 TcpClient client = server.AcceptTcpClient(); // 获取客户端的网络流 NetworkStream stream = client.GetStream(); byte[] data = new byte[1024]; // 读取客户端发送的数据 int bytesRead = stream.Read(data, 0, data.Length); string message = System.Text.Encoding.ASCII.GetString(data,0, bytesRead); Console.WriteLine("Received message: " + message); stream.Close(); client.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (server != null) server.Stop(); } } } ``` 这些是TcpClientTcpListener的基本用法示例。你可以根据你的需求进行进一步的开发和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未来无限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值