首页 > 其他分享 >tcp ip socket seer agv 连接

tcp ip socket seer agv 连接

时间:2024-02-15 12:22:40浏览次数:26  
标签:return socket ip tcp Marshal private new byte public

Dotnet.Seer/SeerSocket.cs

using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace Seer.SeerSocket;
public struct SeerMessageHead
{
    public byte sync;  // 0x5A
    public byte version; // 0x01
    public ushort number; // 0-65536
    public uint length; // 数据区长度,json序列化数据长度
    public ushort type; // 报文的类型

#pragma warning disable 0414 //禁用警告
#pragma warning disable 0169 //禁用警告
    private readonly byte ref0;      //保留
    private readonly byte ref1;      //保留
    private readonly byte ref2;      //保留
    private readonly byte ref3;      //保留
    private readonly byte ref4;      //保留
    private readonly byte ref5;      //保留
#pragma warning restore 0414 //恢复警告
#pragma warning restore 0169 //恢复警告


    public SeerMessageHead()
    {
        this.sync = 0x5A;
        this.version = 0x01;
        this.number = 0x0001;
    }
    public SeerMessageHead(ushort type)
    {
        this.type = type;
    }





    public readonly byte[] ToBytes()
    {

        int size = Marshal.SizeOf(this);
        byte[] bytes = new byte[size];

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(this, ptr, true);
        Marshal.Copy(ptr, bytes, 0, size);
        Marshal.FreeHGlobal(ptr);

        if (BitConverter.IsLittleEndian)
        {
            Array.Reverse(bytes, 2, 2);
            Array.Reverse(bytes, 4, 4);
            Array.Reverse(bytes, 8, 2);
        }
        return bytes;

    }


};



public class SeerSocket
{
    private const string IpAddress = "127.0.0.1";
    private readonly Dictionary<int, TcpClient> clients;

    public SeerSocket(bool onlyRead = true)
    {
        this.clients = new Dictionary<int, TcpClient>
        {
            { 19204, new TcpClient(IpAddress, 19204) }
        };
        if (onlyRead) return;
        this.clients.Add(19205, new TcpClient(IpAddress, 19205));
        this.clients.Add(19206, new TcpClient(IpAddress, 19206));
        this.clients.Add(19207, new TcpClient(IpAddress, 19207));
        this.clients.Add(19210, new TcpClient(IpAddress, 19210));
    }

    // 使用键来访问特定的TcpClient对象
    private TcpClient GetClient(int port)
    {
        return clients[port];
    }


    public string Send(ushort type, string msg = "", int port = 19204)
    {
        var msgBody = NormalStrToHexByte(msg);
        var msgHead = CreateMsgHead(type, (uint)msgBody.Length);
        var response = this.SendRaw(msgHead, msgBody, port);
        return response;
    }

    private string SendRaw(byte[] msgHead, byte[] msgBody, int port)
    {
        try
        {
            TcpClient client = this.GetClient(port);
            if (!client.Connected)
            {
                this.clients[port] = new TcpClient(IpAddress, port);
                Console.WriteLine($"{IpAddress}:{port}:断开连接");
                return "fail";
            }

            NetworkStream serverStream = client.GetStream();
            serverStream.Write(msgHead, 0, msgHead.Length);
            serverStream.Write(msgBody, 0, msgBody.Length);
            serverStream.Flush();

            byte[] inStream = new byte[16];
            while (16 != serverStream.Read(inStream, 0, 16))
            {
                Thread.Sleep(20);
            }
            var recv_head = BytesToStructure<SeerMessageHead>(inStream);
            byte[] recvbyte = BitConverter.GetBytes(recv_head.length);
            Array.Reverse(recvbyte);
            // 获取数据区的长度
            var dsize = BitConverter.ToUInt32(recvbyte, 0);
            const int bufferSize = 512;
            List<byte> datalist = new List<byte>();
            int count = 0;
            while (true)
            {
                byte[] buffer = new byte[bufferSize];
                int readSize = serverStream.Read(buffer, 0, bufferSize);
                count += readSize;
                datalist.AddRange(buffer);
                if (count == dsize)
                {
                    break;
                }
            }
            // var content = BitConverter.ToString(SeerMessageHeadToBytes(recv_head)).Replace("-", " ");
            // Console.WriteLine(content);
            string resMsg = System.Text.Encoding.UTF8.GetString(datalist.ToArray());
            return resMsg;
        }
        catch (SocketException)
        {
            return "fail";
        }
        catch (IOException)
        {
            return "fail";
        }
    }

    public void CloseAll(){
        foreach(var client in this.clients.Values){
            client.Close();
        }
    }

    private T BytesToStructure<T>(byte[] bytesBuffer)
    {
        if (bytesBuffer.Length < Marshal.SizeOf(typeof(T)))
        {
            throw new ArgumentException("size error");
        }

        nint bufferHandler = Marshal.AllocHGlobal(bytesBuffer.Length);

        for (int index = 0; index < bytesBuffer.Length; index++)
        {
            Marshal.WriteByte(bufferHandler, index, bytesBuffer[index]);
        }

        // T? structObject = (T)Marshal.PtrToStructure(bufferHandler, typeof(T));
        T? structObject = Marshal.PtrToStructure<T>(bufferHandler);

        Marshal.FreeHGlobal(bufferHandler);

        if (structObject == null)
        {
            throw new InvalidOperationException("Failed to convert bytes to structure.");
        }

        return structObject!;
    }

    private byte[] NormalStrToHexByte(string str)
    {
        byte[] result = new byte[str.Length];

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);

        for (int i = 0; i < buffer.Length; i++)
        {
            result[i] = Convert.ToByte(buffer[i].ToString("X2"), 16);
        }
        return result;
    }

    private byte[] CreateMsgHead(ushort type, uint msgLen)
    {
        var msgHead = new SeerMessageHead
        {
            type = type,
            length = msgLen
        };
        return msgHead.ToBytes();
    }

    public static void PrintBytes(byte[] bytes)
    {
        foreach (byte b in bytes)
        {
            Console.Write("{0:X2} ", b);
        }

    }





}



Dotnet.Seer/Dotnet.Seer.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Dotnet.Seer/Program.cs

using Seer.SeerSocket;

var seer = new SeerSocket();

while (true)
{
    var msg = seer.Send(0x0410, """{"motor_names": ["motor1"]}""", 19204);
    Console.WriteLine(msg);
    Thread.Sleep(2000);
}

标签:return,socket,ip,tcp,Marshal,private,new,byte,public
From: https://www.cnblogs.com/zhuoss/p/18016139

相关文章

  • JavaScript中的querySelector()方法是什么,它是如何工作的?
    在JavaScript中,有时您需要访问HTML元素。querySelector方法是一个WebAPI,它选择与传入的指定CSS选择器匹配的第一个元素。但是,更详细地说,这是如何工作的呢?在本文中,我们将看一些如何使用querySelector方法以及querySelectorAll方法的示例。(本文内容参考:java567.com)querySelector......
  • NOIP2023 集训做题笔记
    杂项CF1181E2AStoryofOneCountry(Hard)启发式分裂发现如果当前矩形中有一整行或一整列没有穿过城堡内部,就可以分为\(2\)部分而且分开后相当于限制减少,每次贪心的能分就分,朴素实现复杂度为\(O(n^2\logn)\),可通过easyversion考虑优化每次找分割点的过程如果分割点......
  • javascript export default
    概述exportdefault每个js文件或组件,只能有一个;import的时候,不加花括号。其余的,可以多个export,import的时候需要加花括号。示例test.jsvarinfo={name:'zs',age:20}exportvarname1='张三'exportfunctionf1(){return'王五'}varname2='李四'functi......
  • P1012 [NOIP1998 提高组] 拼数
    [NOIP1998提高组]拼数题目描述设有\(n\)个正整数\(a_1\dotsa_n\),将它们联接成一排,相邻数字首尾相接,组成一个最大的整数。输入格式第一行有一个整数,表示数字个数\(n\)。第二行有\(n\)个整数,表示给出的\(n\)个整数\(a_i\)。输出格式一个正整数,表示最大的整数样......
  • TCP和UDP面试题提问
    @目录TCPUDP总结应用TCP(传输控制协议)和UDP(用户数据报协议)是两种计算机网络通信协议,它们在网络通信中起着不同的作用。TCPTCP是面向连接的协议,它在数据传输之前需要在发送端和接收端建立一条连接。TCP提供可靠的数据传输,它使用确认和重传机制来确保数据的可靠性和完整性。T......
  • P1068 [NOIP2009 普及组] 分数线划定
    [NOIP2009普及组]分数线划定题目描述世博会志愿者的选拔工作正在A市如火如荼的进行。为了选拔最合适的人才,A市对所有报名的选手进行了笔试,笔试分数达到面试分数线的选手方可进入面试。面试分数线根据计划录取人数的\(150\%\)划定,即如果计划录取\(m\)名志愿者,则面试分数......
  • javascript import export 简单示例
    概述import是ES6引入的新特性,它允许你以声明式的方式导入其他模块中的内容。require是Node.js中的特性,它允许你使用一个函数来加载和导入其他模块。使用方法utils.jsexportconstadd=(a,b)=>a+b;exportconstsubtract=(a,b)=>a-b; index.jsimport*asutilsfrom......
  • Debug : kfp.Client().upload_pipeline(): Failed to start a transaction to create
    [ERROR:Failedtostartatransactiontocreateanewpipelineandanewpipelineversion:dialtcp:lookupmysqlon10.96.0.10:53:nosuchhost","]>>>kfp.Client().upload_pipeline("/home/maye/pipeline_wafer_distribute.yaml",......
  • 短路在JavaScript中是如何工作的?
    在JavaScript中,理解真实和虚假的值是编写高效简洁代码的基础。结合短路的概念,开发人员可以编写优雅的解决方案来应对常见的编程挑战。在本实践指南中,我们将探讨真实值和虚假值,并了解JavaScript中短路的机制。您可以从这里获取所有源代码。(本文内容参考:java567.com)目录了......
  • 如何在 JavaScript 中比较两个日期 – 技术、方法和最佳实践
    在JavaScript中,您可以使用date对象有效地处理应用程序中的日期、时间和时区。Date对象可帮助您有效地操作数据、处理各种与日期相关的任务,并在创建实际应用程序时执行一些计算。(本文内容参考:java567.com)在本文中,我们将了解以下主题:日期比较概述日期比较在JavaScript......