gpt4 book ai didi

javascript - 将消息从C#客户端发送到Socket到node.js + socket.io服务器

转载 作者:行者123 更新时间:2023-12-03 11:55:39 27 4
gpt4 key购买 nike

我想通过C#Windows Store应用客户端通过套接字向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) {} );

无论如何,有什么我可以让这个东西起作用的吗?

谢谢你。

最佳答案

这是应用程序服务器端(节点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
}

这是我的工作解决方案

关于javascript - 将消息从C#客户端发送到Socket到node.js + socket.io服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28694205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com