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. }

相关文章
VSPD虚拟串口软件安装及使用
VSPD虚拟串口软件安装及使用
3988 0
|
6月前
|
物联网
(手把手)在华为云、阿里云搭建自己的物联网MQTT消息服务器,免费IOT平台
本文介绍如何在阿里云搭建自己的物联网MQTT消息服务器,并使用 “MQTT客户端调试工具”模拟MQTT设备,接入平台进行消息收发。
2364 42
|
8月前
|
人工智能 数据挖掘 API
3个实操案例,带你体验真正流畅可用的企业级通用智能体
本文探讨了企业级通用智能体的现状与应用,重点介绍了实在Agent。文章指出,当前通用AI Agent分为两类:一类是类似Manus的产品,采用大模型+API模式;另一类是在RPA基础上融合AI Agent架构的产品。实在Agent属于后者,具备低门槛、简单直白的操作方式和随心掌控的执行过程。文中通过豆瓣电影数据获取、多平台舆情分析及剪映图文成片自动化三个案例,展示了实在Agent的实际应用能力。此外,文章还强调了企业级智能体需具备可控、稳定和高效的特性,并总结了实在Agent满足商业化落地的核心能力,包括企业知识库、业务系统操作指南、模型接入支持及私有化部署等。
1021 8
|
算法 vr&ar C#
使用Unity进行虚拟现实开发:深入探索与实践
【8月更文挑战第24天】使用Unity进行虚拟现实开发是一个充满挑战和机遇的过程。通过掌握Unity的VR开发技术,你可以创造出令人惊叹的VR体验,为用户带来前所未有的沉浸感和乐趣。随着技术的不断进步和应用场景的不断拓展,VR开发的未来充满了无限可能。希望本文能为你提供有用的指导和启发!
|
算法 Python
群智能算法:【WOA】鲸鱼优化算法详细解读
本文详细解读了鲸鱼优化算法(WOA),这是一种受鲸鱼捕食行为启发的新兴群体智能优化算法,具有强大的全局搜索能力和快速收敛速度。文章分为五个部分,分别介绍了引言、算法原理、主要步骤、特点及Python代码实现。通过模拟鲸鱼的捕食行为,该算法能够在复杂的优化问题中找到全局最优解。
|
消息中间件 传感器 网络协议
阿里云MQTT简介和使用流程
以下是内容的摘要: 该文主要介绍了在阿里云上搭建 MQTT 服务器的步骤。首先,需要注册阿里云账号并进行实名认证。然后,购买阿里云 MQTT 实例,选择合适的类型、地域、连接和消息限制。接着,创建产品和设备,命名并上线,获取 MQTT 连接的相关信息,包括 ProductKey、DeviceName 和 DeviceSecret。通过提供的 MQTT.fx 工具,设置 MQTT 客户端连接参数,包括 Broker 地址、端口、用户名和密码。最后,使用 MQTT.fx 测试连接,实现数据的上报和接收,验证 MQTT 服务器的配置是否成功。
|
存储 缓存 物联网
MQTT常见问题之MQTT发送消息过多内存不够处理不过来如何解决
MQTT(Message Queuing Telemetry Transport)是一个轻量级的、基于发布/订阅模式的消息协议,广泛用于物联网(IoT)中设备间的通信。以下是MQTT使用过程中可能遇到的一些常见问题及其答案的汇总:
|
存储 传感器 移动开发
嵌入式系统中详解 Modbus 通信协议(清晰易懂)
嵌入式系统中详解 Modbus 通信协议(清晰易懂)
4272 1
|
存储 网络协议 物联网
C语言代码封装MQTT协议报文,了解MQTT协议通信过程
MQTT是一种轻量级的通信协议,适用于物联网(IoT)和低带宽网络环境。它基于一种“发布/订阅”模式,其中设备发送数据(也称为 “发布”)到经纪人(称为MQTT代理),这些数据被存储,并在需要时被转发给订阅者。这种方式简化了网络管理,允许多个设备在不同的网络条件下进行通信(包括延迟和带宽限制),并支持实时数据更新。它是开放的,可免费使用并易于实施。
834 0
|
消息中间件 存储 运维
难住了,微服务之间的几种调用方式哪种最佳?
难住了,微服务之间的几种调用方式哪种最佳?