首页 > 其他分享 >NetCore 使用 SimpleTCP 实现双工通信

NetCore 使用 SimpleTCP 实现双工通信

时间:2024-10-09 17:01:16浏览次数:1  
标签:双工 Console NetCore System server SimpleTCP client using Server

十年河东,十年河西,莫欺少你穷

学无止境,精益求精

1、新建 netcore 控制台应用程序并引入包

 2、服务端

using SimpleTCP;
using System;
using System.Net;
using System.Text;

namespace TcpServe
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new SimpleTcpServer();
            //设置编码格式,默认是UTF8
            server.StringEncoder = System.Text.ASCIIEncoding.UTF8;
            server.Delimiter = Encoding.ASCII.GetBytes("\r")[0];
            server.Start(IPAddress.Parse("127.0.0.1"), 8080);
            server.ClientConnected += Server_ClientConnected;
            server.ClientDisconnected += Server_ClientDisconnected;
            server.DataReceived += Server_DataReceived;

            Console.ReadKey();

        }

        private static void Server_DataReceived(object sender, Message e)
        {

            Console.WriteLine("收到来自客户端的信息[" + e.TcpClient.Client.RemoteEndPoint.ToString() + "]" + e.MessageString);

            e.Reply(":"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private static void Server_ClientDisconnected(object sender, System.Net.Sockets.TcpClient e)
        {
            Console.WriteLine("客户端断开信息[" + e.Client.RemoteEndPoint.ToString() + "]");
        }

        private static void Server_ClientConnected(object sender, System.Net.Sockets.TcpClient e)
        {

            Console.WriteLine("客户端连接信息[" + e.Client.RemoteEndPoint.ToString() + "]");
        }
    }
}
View Code

3:客户端

using SimpleTCP;
using System;
using System.Text;
using System.Threading.Tasks;

namespace TcpService
{
    class Program
    {
        static void Main(string[] args)
        {
            //初始化
            var client = new SimpleTcpClient();
           

            //设置编码格式,默认是UTF8
            client.StringEncoder = System.Text.ASCIIEncoding.UTF8;
            //设置分隔符,默认是0x13
            client.Delimiter = Encoding.ASCII.GetBytes("\r")[0];

            //收到数据的事件,可以在这里实现自己的协议
            client.DataReceived += (sender, msg) =>
            {

                //字符串消息
                Console.WriteLine("收到来自服务器的消息:"+ msg.MessageString);
            };

            bool exit = false;
            bool connected = false;
            Task.Factory.StartNew(() =>
            {
                while (!exit)
                {
                    try
                    {
                        if (connected)
                        {
                            //发送心跳
                            client.Write(":"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            Task.Delay(2000).Wait();
                        }
                        else
                        {
                            //断线重连
                            client.Connect("127.0.0.1", 8080);
                            connected = true;
                            Task.Delay(1000).Wait();
                        }
                    }
                    catch (Exception)
                    {
                        connected = false;
                        client.Disconnect();
                    }
                }
            }, TaskCreationOptions.LongRunning);

            Console.ReadKey(); 

        }
    }
}
View Code

4、运行结果

 开启了多个客户端

标签:双工,Console,NetCore,System,server,SimpleTCP,client,using,Server
From: https://www.cnblogs.com/chenwolong/p/18454662

相关文章

  • UART通信,上下位机全双工通信出现堵塞延时。
    使用Ubuntu系统作为上位机,多线程开发时,使用其中一个线程专门作为通信使用。使用tc264作为下位机,使用同一UART分别进行数据接收和数据传输问题:当上位机把数据传输和接收的代码都放入同一线程中时,上位机接收和传输速率受到影响,延迟增强,时效性降低。但UART是全双工异步串行通信,......
  • 清华:LLM解码策略实现双工对话
    ......
  • C#(.NetCore)接入AD域用户的实现
      很多公司电脑都是windows,而对用户的管理则很多采用AD域的形式来管理,本文简单的来介绍一下.NetCore中怎么接入AD域来实现登录等操作。  首先,我这里使用的是.net6,其它版本类似。  其次,这里假设你已经对AD域有了基本的了解,比如AD域所使用的LDAP、属性等,如果不了解先自行百......
  • netCore中的内置日志的使用
    1、netCore3.1中配置  参考链接: https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Hosting;......
  • .NetCore MySqlException 多线程中(There is already an open DataReader associated w
    问题描述:其实标题只是遇到问题的其中之一,遇到三种异常信息如下:Lockwaittimeoutexceeded;tryrestartingtransaction大概意思:超过锁定等待超时;尝试重新启动事务 ThereisalreadyanopenDataReaderassociatedwiththisConnectionwhichmustbeclosedfirst.大......
  • 盘点3款.NetCore(C#)开源免费商城系统
    CoreShop商城介绍核心商城系统(CoreShop) 是基于Asp.Net8.0、Uni-App开发、支持可视化布局的小程序商城系统;前后端分离,支持跨平台运行;拥有分销、代理、团购秒杀、接龙、拼团、直播、优惠券、自定义表单等众多营销功能,拥有完整SKU、下单、售后、物流流程,支持可视化自定义首......
  • NetCore Channel-生产者&消费者
    usingSystem.Threading.Channels;namespaceChannelDemo{publicclassChannelMgr{//优势//允许开发者根据需要创建具有固定容量(有界)或无限容量(无界)的通道//staticChannel<string>channel=Channel.CreateBounded<strin......
  • NetCore DynamicExpresso 动态表达式使用例子
    Simple.cs简单使用例子usingDynamicExpresso;namespaceDynamicExpressoDemo{classCustomer{publicstringName{get;set;}}publicclassSimple{publicstaticvoidTest(){//返回结果Interpreter......
  • C# .netcore NPOI库 实现报表的列自适应删减
    实际需求:业务上的一个需求,数据库表A中的B字段存放的是该条数据的一些标签,标签存在两级【即一级标签和二级标签】,现在要是实现将这些标签统计到报表中,一级标签作为表头,二级标签作为填充值。由于之前的报表每增加一个列都需要去数据库表中增加这个字段名称,然后代码中写统计逻辑,这......
  • asp.netcore8 + vue3 + mysql 自用记账项目(四)项目部署
    一、生成后台api服务 1、在系统生成的Dockerfile基础上,添加时区标识FROMmcr.microsoft.com/dotnet/aspnet:8.0ASbaseENVTZAsia/ShanghaiRUNln-snf/usr/share/zoneinfo/$TZ/etc/localtime&&echo$TZ>/etc/timezoneWORKDIR/appEXPOSE80EXPOSE443FROMmcr.......