首页 > 其他分享 >socket

socket

时间:2024-09-21 15:48:08浏览次数:9  
标签:Task socket buffer await static var

Server

 internal class Program
 {
     static async Task Main(string[] args)
     {
         var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);

         var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
         socket.Bind(endpoint);
         socket.Listen(100);

         var e = new SocketAsyncEventArgs();
         e.UserToken = socket;
         e.Completed += Args_Completed!;

         if (!socket.AcceptAsync(e))
         {
             OnAccepted(e);
         }

         Console.ReadKey();
     }

     private static void Args_Completed(object sender, SocketAsyncEventArgs e)
     {
         OnAccepted(e);
     }

     private static void OnAccepted(SocketAsyncEventArgs e)
     {
         if (e.LastOperation == SocketAsyncOperation.Accept &&
            e.SocketError == SocketError.Success &&
            e.AcceptSocket != null)
         {
             // 处理新连接
             Console.WriteLine("接收到新连接");
             Task.Factory.StartNew(ProcessLinesAsync!, e.AcceptSocket);
         }

         // 监听下一连接
         e.AcceptSocket = null;

         try
         {
             if (!((Socket)e.UserToken!).AcceptAsync(e))
             {
                 OnAccepted(e);
             }
         }
         catch (Exception ex)
         {
             // 如果处于运行状态,记录日志
             Console.WriteLine(ex.ToString());
             // 销毁实例
         }
     }

     private static async Task ProcessLinesAsync(object state)
     {
         var socket = (Socket)state;

         // 开启管道,一边读,一边写
         var pipe = new Pipe();
         Task writing = FillPipeAsync(socket, pipe.Writer);
         Task reading = ReadPipeAsync(pipe.Reader);

         await Task.WhenAll(reading, writing);
     }

     private static async Task ReadPipeAsync(PipeReader reader)
     {
         while (true)
         {
             ReadResult result = await reader.ReadAsync();
             ReadOnlySequence<byte> buffer = result.Buffer;

             while (TryReadLine(ref buffer, out ReadOnlySequence<byte> line))
             {
                 // Process the line.
                 Console.WriteLine(Encoding.UTF8.GetString(line));
             }

             // Tell the PipeReader how much of the buffer has been consumed.
             reader.AdvanceTo(buffer.Start, buffer.End);

             // Stop reading if there's no more data coming.
             if (result.IsCompleted)
             {
                 break;
             }
         }

         // Mark the PipeReader as complete.
         await reader.CompleteAsync();
     }

     static bool TryReadLine(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line)
     {
         // Look for a EOL in the buffer.
         SequencePosition? position = buffer.PositionOf((byte)'\n');

         if (position == null)
         {
             line = default;
             return false;
         }

         // Skip the line + the \n.
         line = buffer.Slice(0, position.Value);
         buffer = buffer.Slice(buffer.GetPosition(1, position.Value));

         return true;
     }

     async static Task FillPipeAsync(Socket socket, PipeWriter writer)
     {
         const int minimumBufferSize = 10;

         while (true)
         {
             // 分配内存
             Memory<byte> memory = writer.GetMemory(minimumBufferSize);

             try
             {
                 var bytesRead = await socket.ReceiveAsync(memory, SocketFlags.None);
                 if (bytesRead == 0)
                 {
                     break;
                 }

                 // 告诉PipeWriter已经写入了多少字节
                 writer.Advance(bytesRead);
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex);
                 break;
             }

             // 标记写入完成
             FlushResult result = await writer.FlushAsync();

             if (result.IsCompleted)
             {
                 break;
             }
         }

         await writer.CompleteAsync();
     }
 }

Client
internal class Program
{
private static Stream stream;

    static async Task Main(string[] args)
    {
        var client = new TcpClient();
        await client.ConnectAsync("localhost", 5000);
        var stream = client.GetStream();
        await ProcessLinesAsync(stream);
        Console.ReadKey();
    }

    async static Task ProcessLinesAsync(NetworkStream stream)
    {
        while (true)
        {
            var str = "一个商户可以关联多个小程序,一个小程序也可以绑定多个商户。对应日常开发,在多商户的情况,每一个商户号在后台都会进行配置,存入数据库,支付时根据当前不同的账户决定使用那一个商户号,这一块需要后台对每一个AppId和商户号做关联,支付时才能确认具体使用那个商户号。Hello world\n";
            var bytes = Encoding.UTF8.GetBytes(str);
            await stream.WriteAsync(bytes, 0, bytes.Length);
            Thread.Sleep(2000);
        }
    }
}

标签:Task,socket,buffer,await,static,var
From: https://www.cnblogs.com/readafterme/p/18424096

相关文章

  • Golang在线客服系统源码:基于Gin框架,Websocket即时通讯企业网站客服聊天源码,包括后台管
    唯一客服系统是一款基于Golang的Gin框架构建的在线客服解决方案,支持独立部署,确保数据的私密性和安全性。它具备自适应的响应式设计,能够完美适配PC端、移动端以及APP内嵌等多种场景。客服端提供PC后台管理功能,实现实时消息接收和交流。此外,为了满足移动端回复需求,系统还利用uniapp......
  • socket close和shutdown的区别,TIME_WAIT和CLOSE_WAIT
    TCP主动关闭连接 appl:close(),-->FINFIN_WAIT_1//主动关闭socket方,调用close关闭socket,发FIN              <--ACKFIN_WAIT_2//对方操作系统的TCP层,给ACK响应。然后给FIN              <--FIN              -->ACK"TI......
  • 0915,SOCKET网络编程部分,三种I/O多路复用模型(select ,poll,epoll)
    目录  nc127.0.0.1port01_socket_client.cc01_socket_server.cc02_select_client.cc02_select_server.cc03_poll_server.cc04_epoll_server.cc01_socket_client.cc#include<stdlib.h>#include<string.h>#include<sys/stat.h>#include<sy......
  • torch.distributed.DistNetworkError: The server socket has failed to listen on an
    解决方案是在torchrun中添加参数--master_port改变masterport。且注意这个参数一定要加在要跑的文件即src/entry_point/train.py之前,否则会被忽略。引用:https://juejin.cn/post/7260668104752775228我的代码是:torchrun--nproc_per_node1--master_port29501-mtraining.......
  • Websocket防护的重要性及应对策略:快快网络专家团队的创新实践
    WebSocket(WSS)因其双向和全双工通信的特点,在现代网络通信中得到广泛应用,尤其是在需要低延迟和实时数据交互的场景中。然而,随着WebSocket的普及,其安全性问题也日益凸显,各种针对WSS的攻击手段层出不穷,给企业的数据安全带来了严峻的挑战。针对WSS的攻击具有多样性和隐蔽性。其中,最......
  • # 利刃出鞘_Tomcat 核心原理解析(十一)-- Tomcat 附加功能 WebSocket -- 3
    利刃出鞘_Tomcat核心原理解析(十一)--Tomcat附加功能WebSocket–3一、Tomcat专题-WebSocket-案例-OnMessage分析1、WebSocketDEMO案例实现流程分析:OnMessage分析2、在项目dzs168_chat_room中,在websocket类ChatSocket.java中,创建publicvoidonMes......
  • Can't connect to local MySQL server through socket
    mysql-urootERROR2002(HY000):Can'tconnecttolocalMySQLserverthroughsocket'/tmp/mysql.sock'(2)这是mysql登录时找不到套接字的问题。首先需要明白的是,Linux端的mysqlserver启动时会开启一个socket,Linux上的MySQL的客户端在不使用IP连接时mysqlserver时,默认......
  • C#实现Socket客户端
    usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;u......
  • Netty WebSocket 最简单的聊天室
    Netty最为后端服务处理WebSocket协议连接后端代码pom.xml<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xs......
  • Java结合WebSocket 实现简单实时双人协同 pk 答题
    引入实现过程WebSocket后端1、实体类2、异常处理类3、游戏状态枚举类4、ws主类5、配置类及工具类引入引入与技术选型:在实时互动应用中,实现流畅的多人协同对战功能是一大挑战。WebSocket技术,以其全双工通信能力,提供了解决方案。不同于传统HTTP请求的短连接,WebSocket建立持久连接,极......