簡體   English   中英

Send Message to Socket, 從C#客戶端到node.js + socket.io服務器

[英]Send Message to Socket, from C# client to node.js + socket.io server

我想通過帶有 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");

//});

消息“Hello”正確出現在我的客戶端,問題是當我添加這些行時,代碼不再起作用。

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

我發送的消息只是一個字符串。 這條消息似乎不正確。

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

無論如何,我可以讓這件事起作用嗎?

謝謝你。

這是應用程序服務器端(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
        }

這是我的工作解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM