1

C#我正在为 Milestone VMS 开发一个 MIP 插件。使用 C# 连接到 SocketIO 时出现问题。我尝试使用 TcpClient、Socket、ClientWebSocket 连接到 SocketIO


    TcpClient tcpClient = new TcpClient();

    tcpClient.Connect("127.0.0.1, 3001);

我也尝试与 ClientWebSocket 连接,但服务器端再次没有反应。

    using (var client = new ClientWebSocket())
                {
                    // await client.ConnectAsync(new Uri("ws://192.168.100.25:8090/?token="),timeout.Token);
                    await client.ConnectAsync(new Uri(LOCAL_PATH), timeout.Token);
                    var buffer = new ArraySegment<byte>(new byte[1000]);

                    var result = await client.ReceiveAsync(buffer, timeout.Token);
                }

任何人都可以提供一些可以作为 SocketIO 客户端的库吗?

URI 有这样的语法: http: //127.0.0.1 :3001?token=xxx

4

1 回答 1

0

这是我使用的经过测试的代码,假设您的服务器正在运行,您需要传递 IP 或主机名和端口号,然后输入您要发送的有效负载或消息:

private bool ConnectAndSendMessage(String server, Int32 port, String message)
    {
        try
        {
            // Create a TcpClient.
            TcpClient client = new TcpClient(server, port);

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

            // Get a client stream for reading and writing.
            NetworkStream stream = client.GetStream(); 

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


            // Buffer to store the response bytes receiver from the running server.
            data = new Byte[256];

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

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

            // Close everything.
            stream.Close();
            client.Close(); return true;
        }
        catch (ArgumentNullException e)
        {
            _txtStyling.WriteCustomLine(string.Format("ArgumentNullException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
        }
        catch (SocketException e)
        {
            _txtStyling.WriteCustomLine(string.Format("SocketException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
        }
    }
于 2020-01-14T12:56:57.900 回答