我花了很多时间试图弄清楚我的代码有什么问题,我知道有很多信息,但不是它似乎解决了我的问题。
我设法从UNITY应用程序接收数据,但它不能从c#开始工作。
这是我的Node.js服务器代码:
var server = require('http').createServer()
, url = require('url')
, WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ server: server })
, express = require('express')
, app = express()
, port = 8080;
app.use(function (req, res) {
res.send({ msg: "hello" });
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('Trying to send information');
});
这是我的c#代码: 这就是我的联系方式:
private void Connect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse("***********"), 8080);
}
catch (SocketException)
{
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
lb_stt.Text = ("Connected!");
}
这是我发送数据的方式
private void btnSend_Click(object sender, EventArgs e)
{
if (_clientSocket.Connected)
{
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("10.186.139.115"), 8080);
try
{
byte[] buffer = Encoding.ASCII.GetBytes("check");
int its = _clientSocket.Send(buffer);
MessageBox.Show((its.ToString()));//Output:5 This shows that my C# code apparently sends the data
}
catch (Exception error)
{
//_clientSocket.Disconnect(true);
MessageBox.Show(error.Message);
}
}
}
我对Node.js有非常基本的了解,所以如果问题很简单,我会道歉。
问题是,当我点击c#中的按钮时,我无法在node.js服务器中接收信息,尽管我在c#应用程序中连接到服务器..
另一个问题是,如果我还想使用ws.send或ws.broadcast来传输来自传感器的数据? (https://github.com/websockets/ws)