【问题标题】:Send Message to Socket, from C# client to node.js + socket.io server向 Socket 发送消息,从 C# 客户端到 node.js + socket.io 服务器
【发布时间】:2015-04-25 23:34:13
【问题描述】:

我想通过带有 c# windows store app 客户端的套接字向 node.js 和 socket.io 服务器发送消息

我的客户端代码是这样的(c#)

private async void SendDatatoSocket(string sendTextData)
    {
        if (!connected)
        {
            StatusText = "Must be connected to send!";
            return;
        }

        Int32 wordlength = 0; // Gets the UTF-8 string length.

        try
        {
            OutputView = "";
            StatusText = "Trying to send data ...";
            txtblock_showstatus.Text += System.Environment.NewLine;
            txtblock_showstatus.Text += StatusText;
            Debug.WriteLine(StatusText);
            // add a newline to the text to send
            string sendData = sendTextData + Environment.NewLine;
            DataWriter writer = new DataWriter(clientSocket.OutputStream);
            wordlength = sendData.Length; // Gets the UTF-8 string length.

            // Call StoreAsync method to store the data to a backing stream
            await writer.StoreAsync();

            StatusText = "Data was sent" + Environment.NewLine;
            txtblock_showstatus.Text += System.Environment.NewLine;
            txtblock_showstatus.Text += StatusText;
            Debug.WriteLine(StatusText);
            // detach the stream and close it
            writer.DetachStream();
            writer.Dispose();

        }
        catch (Exception exception)
        {
            // If this is an unknown status, 
            // it means that the error is fatal and retry will likely fail.
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }

            StatusText = "Send data or receive failed with error: " + exception.Message;
            txtblock_showstatus.Text += System.Environment.NewLine;
            txtblock_showstatus.Text += StatusText;
            Debug.WriteLine(StatusText);
            // Could retry the connection, but for this simple example
            // just close the socket.

            closing = true;
            clientSocket.Dispose();
            clientSocket = null;
            connected = false;

        }

        // Now try to receive data from server
        try
        {
            OutputView = "";
            StatusText = "Trying to receive data ...";
            Debug.WriteLine(StatusText);
            txtblock_showstatus.Text += System.Environment.NewLine;
            txtblock_showstatus.Text += StatusText;



            DataReader reader = new DataReader(clientSocket.InputStream);

            string receivedData;
            reader.InputStreamOptions = InputStreamOptions.Partial;

            var count = await reader.LoadAsync(512);
            if (count > 0)
            {
                receivedData = reader.ReadString(count);
                Debug.WriteLine(receivedData);
                txtblock_showstatus.Text += System.Environment.NewLine;
                txtblock_showstatus.Text += receivedData;
            }


        }

        catch (Exception exception)
        {
            // If this is an unknown status, 
            // it means that the error is fatal and retry will likely fail.
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }

            StatusText = "Receive failed with error: " + exception.Message;
            Debug.WriteLine(StatusText);
            // Could retry, but for this simple example
            // just close the socket.

            closing = true;
            clientSocket.Dispose();
            clientSocket = null;
            connected = false;

        }
    }

我在服务器端的代码是这样的(node.js)

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 1337;

// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function (sock) {

// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

sock.on('data', function (data) {
    console.log(sock.name + "> " + data, sock);
});

// Add a 'close' event handler to this instance of socket
sock.on('close', function (data) {
    console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    sock.end();
});
}).listen(PORT, HOST);

之前,我把node.js代码改成了

net.createServer(function (sock) {

console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

sock.write("Hello");

//});

消息“你好”正确出现在我的客户端 问题是当我添加这些行时,代码不再起作用了。

sock.on('data', function (data) {
    console.log(sock.name + "> " + data, sock);
});

我发送的消息只是一个字符串。 似乎该消息不正确。

sock.on('data', function (data) {} );

有没有什么办法可以让这件事发挥作用?

谢谢。

【问题讨论】:

    标签: javascript c# node.js sockets socket.io


    【解决方案1】:

    这是应用服务器端(Node Js):

    var net = require('net');
    
    var server = net.createServer(function(socket) { //Create the server and pass it the function which will write our data
      console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort);
        socket.write("Hello\n");
        socket.write("World!\n");
        //when to open the C # application write in the Desktop console "hello world"
            socket.on('data', function (data) {
            console.log(socket.name + "> " + data);
            socket.write("Message from server to Desktop");
            socket.end("End of communications.");
          });
    
    });
    
    server.listen(3000); //This is the port number we're listening to
    

    在我写的 C# 应用程序中:

     static void Main(string[] args)
            {
                TcpClient client = new TcpClient();
                client.Connect("192.168.x.x", 3000); //Connect to the server on our local host IP address, listening to port 3000
                NetworkStream clientStream = client.GetStream();
                System.Threading.Thread.Sleep(1000); //Sleep before we get the data for 1 second
                while (clientStream.DataAvailable)
                {
                    byte[] inMessage = new byte[4096];
                    int bytesRead = 0;
                    try
                    {
                        bytesRead = clientStream.Read(inMessage, 0, 4096);
                    }
                    catch { /*Catch exceptions and handle them here*/ }
    
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    Console.WriteLine(encoder.GetString(inMessage, 0, bytesRead));
                }
                //******************** SEND DATA **********************************
                string message = "Send message from Desktop to Server NodeJs!";
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
                // Call StoreAsync method to store the data to a backing stream
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);
                Console.WriteLine("Sent: {0}", message);
                // Buffer to store the response bytes.
                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);
                Console.WriteLine("Received: {0}", responseData);
    
                // Close everything.
                stream.Close();
                //*****************************************************************
                client.Close();
                System.Threading.Thread.Sleep(10000); //Sleep for 10 seconds
            }
    

    这是我的工作解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2011-10-05
      • 2013-11-10
      • 2016-07-13
      相关资源
      最近更新 更多