如何将SocketIO与C#客户端连接

问题描述 投票:0回答: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

c# .net socket.io tcpclient milestone
1个回答
0
投票

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

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;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.