TcpClient,TcpListener实现简单通讯

简介: 1、TcpListener类 从 TCP 网络客户端侦听连接。 TcpListener 类提供一些简单方法,用于在阻止同步模式下侦听和接受传入连接请求。可使用 TcpClient 或 Socket 来连接 TcpListener。

1、TcpListener类

从 TCP 网络客户端侦听连接。

 

2、TcpClient类

为 TCP 网络服务提供客户端连接。

TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。


    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.IO;
    6. using System.Net;
    7. using System.Net.Sockets;

    8. namespace TcpListenerDemo
    9. {
    10.     class Program
    11.     {
    12.         static void Main(string[] args)
    13.         {
    14.             TcpListener server = null;
    15.             try
    16.             {
    17.                 /* Set the TcpListener (Server) on port 13000. */
    18.                 Int32 port = 13000;
    19.                 IPAddress localAddr = IPAddress.Parse("127.0.0.1");

    20.                 /* TcpListener server = new TcpListener(port); -----The old API */
    21.                 server = new TcpListener(localAddr, port);

    22.                 /* Start listening for client requests. */
    23.                 server.Start();

    24.                 /* Buffer for reading data */
    25.                 Byte[] bytes = new Byte[256];
    26.                 String data = null;

    27.                 /* Enter the listening loop. */
    28.                 while (true)
    29.                 {
    30.                     Console.Write("I'm Server,Waiting for a connection... ");

    31.                     /*
    32.                     * AcceptTcpClient是一个阻塞型方法,返回用于发送、接收数据的Tcpclient实例。
    33.                     * You could also user server.AcceptSocket() here.
    34.                      */
    35.                     TcpClient client = server.AcceptTcpClient();
    36.                     Console.WriteLine("Connected!");

    37.                     data = null;

    38.                     /* 获取一个stream对象来做reading和writing操作 */
    39.                     NetworkStream stream = client.GetStream();

    40.                     int i;

    41.                     /* Loop to receive all the data sent by the client. */
    42.                     while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    43.                     {
    44.                         /* Translate data bytes to a ASCII string. */
    45.                         data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    46.                         Console.WriteLine("Received From Client: {0}\n", data);

    47.                         /* Process the data sent by the client. */
    48.                         data = data.ToUpper();

    49.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

    50.                         /* Send back a response. */
    51.                         stream.Write(msg, 0, msg.Length);
    52.                         Console.WriteLine("Server Sent Back: {0} Server\n", data);
    53.                     }

    54.                     /* Shutdown and end connection */
    55.                     client.Close();
    56.                 }
    57.             }
    58.             catch (SocketException e)
    59.             {
    60.                 Console.WriteLine("SocketException: {0}", e);
    61.             }
    62.             finally
    63.             {
    64.                 /* Stop listening for new clients. */
    65.                 server.Stop();
    66.             }

    67.             Console.WriteLine("\nHit enter to continue...");
    68.             Console.Read();
    69.         }
    70.     }
    71. }

     

    (2)客户端代码


    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.IO;
    6. using System.Net;
    7. using System.Net.Sockets;

    8. namespace TcpClientDemo
    9. {
    10.     class Program
    11.     {
    12.         static void Connect(String server, String message)
    13.         {
    14.             try
    15.             {
    16.                 /*
    17.                  * Create a TcpClient.
    18.                  * Note, for this client to work you need to have a TcpServer
    19.                  * connected to the same address as specified by the server, port
    20.                  * combination.
    21.                  */
    22.                 Int32 port = 13000;
    23.                 TcpClient client = new TcpClient(server, port);

    24.                 /* Translate the passed message into ASCII and store it as a Byte array. */
    25.                 Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

    26.                 // Get a client stream for reading and writing.
    27.                 // Stream stream = client.GetStream();

    28.                 NetworkStream stream = client.GetStream();

    29.                 /* Send the message to the connected TcpServer. */
    30.                 stream.Write(data, 0, data.Length);

    31.                 Console.WriteLine("Sent: {0}", message);

    32.                 // Receive the TcpServer.response.

    33.                 /* Buffer to store the response bytes. */
    34.                 data = new Byte[256];

    35.                 /* String to store the response ASCII representation. */
    36.                 String responseData = String.Empty;

    37.                 /* Read the first batch of the TcpServer response bytes. */
    38.                 Int32 bytes = stream.Read(data, 0, data.Length);
    39.                 responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    40.                 Console.WriteLine("Received from Server: {0}", responseData);

    41.                 /* Close everything. */
    42.                 stream.Close();
    43.                 client.Close();
    44.             }
    45.             catch (ArgumentNullException e)
    46.             {
    47.                 Console.WriteLine("ArgumentNullException: {0}", e);
    48.             }
    49.             catch (SocketException e)
    50.             {
    51.                 Console.WriteLine("SocketException: {0}", e);
    52.             }

    53.             Console.WriteLine("\n Press Enter to continue...");
    54.             Console.Read();
    55.         }

    56.         static void Main(string[] args)
    57.         {
    58.             while (true)
    59.             {
    60.                 Connect("127.0.0.1", "This is send from client");
    61.             }
    62.         }
    63.     }
    64. }

相关文章
|
消息中间件 算法 Java
弥补延时消息的不足,RocketMQ 基于时间轮算法实现了定时消息!
弥补延时消息的不足,RocketMQ 基于时间轮算法实现了定时消息!
1571 1
弥补延时消息的不足,RocketMQ 基于时间轮算法实现了定时消息!
|
Python
pycharm使用debug的时候遇到断点不停的问题
pycharm使用debug的时候遇到断点不停的问题
1765 0
|
8月前
|
自然语言处理 开发者
LCAS V3.1:解决大模型长文本写崩、出现幻觉的提示词技术
本文介绍原创提示词技术LCAS V3.1(已发表于ResearchSquare预印本),通过纯提示词工程实现大模型长文本生成的强一致性保障:10万字内逻辑错误率<0.5%,关键事实留存率>98%。支持即插即用与开发者嵌入双模部署,适配小说、报告、论文等30+场景,零微调、低成本、高通用。(239字)
|
9月前
|
人工智能 自然语言处理 安全
2026年OpenClaw/Clawdbot阿里云一键部署与72个必备OpenClaw Skills通关指南
在2026年AI智能体产业化落地的关键一年,OpenClaw(原Clawdbot、Moltbot)已从一款开源实验性工具,进化为拥有**3002个社区技能**、GitHub星标突破14.5k的生态级产品。其核心竞争力不仅在于与阿里云百炼、Claude等大模型的深度适配,更在于OpenClaw Skills生态的爆发式增长——截至2026年2月,官方精选的72个高频技能已覆盖内容创作、办公自动化、开发辅助、跨境电商、数据分析、生活服务、思维决策七大核心场景,真正实现“自然语言即指令,AI自动完成任务”。
2136 7
|
11月前
|
JSON 安全 Java
支付宝支付实战全攻略
本文详细介绍了基于JDK17的企业级支付宝支付实现方案。首先阐述了支付宝支付的核心参与者、安全机制和支付场景区分,重点分析了RSA2签名验证流程。随后提供了完整的开发指南,包括开放平台配置、Maven环境搭建、数据库设计以及核心工具类封装。文章详细展示了基于MyBatis-Plus的持久层实现和Swagger3接口文档集成,并重点讲解了支付回调处理、退款功能等核心业务逻辑的实现。针对企业级应用场景,特别强调了幂等性设计、高可用方案和常见问题的解决方案,包括异步通知丢失兜底机制和安全加固措施。
922 2
|
物联网 5G 智能硬件
介绍频段、带宽、频率、调制、解调等基础术语,以及Wi-Fi、蓝牙、ZigBee、UWB、LTE、5G等常见无线通信技术
在无线通信领域,专业术语是理解技术的关键。本文详细介绍了频段、带宽、频率、调制、解调等基础术语,以及Wi-Fi、蓝牙、ZigBee、UWB、LTE、5G等常见无线通信技术,还涵盖了信号传播、信道容量、信噪比等深入概念。通过本文,你将掌握无线技术的核心知识,成为半个无线专家。
2392 4
|
测试技术 Android开发
快速上手App自动化测试利器,Toast原理解析及操作实例
`Toast`是Android中的轻量级通知,短暂显示在屏幕任意位置,1-2秒后自动消失,不获取焦点且不可点击。Appium通过uiautomator2在控件树中处理Toast。在测试中,可设置隐式等待,利用XPath或Accessibility ID定位Toast元素进行检测和验证。示例代码展示了如何初始化driver,点击触发Toast,以及如何定位并读取Toast文本。
|
Linux 开发工具 开发者
智谱ChatGLM3本地私有化部署(Linux)
智谱ChatGLM3本地私有化部署(Linux)
Word有哪些快捷键?
【10月更文挑战第24天】Word有哪些快捷键?
939 4
|
Java 测试技术 应用服务中间件
网盘系统|基于SpringBoot的网盘系统的设计与实现(一)
网盘系统|基于SpringBoot的网盘系统的设计与实现
1028 1

热门文章

最新文章