I'm trying to run a websocket server on node.js (just started learning node) and I have this code:
const net = require('net')
const server = net.createServer((socket) => {
socket.on('text', (data) => {
console.log(data.toString());
});
socket.on('data', (data) => {
console.log(data.toString());
});
});
server.listen(9898, () => {
console.log('Server established on ' + server.address().port);
});
Now, from my phone, I've made an app that connects to the websocket and sends an event of name text
. Now, when I emit the event from my phone, not the text
event runs, but the data
event runs. I get the following log.
GET /socket.io/?EIO=3&transport=polling HTTP/1.1
Host: server2.necrodragon41.repl.co
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1.1; LG-M700 Build/NMF26X)
Accept-Encoding: gzip
X-Forwarded-For: 130.211.1.39
X-Forwarded-Proto: https
X-Replit-User-Id:
X-Replit-User-Name:
X-Replit-User-Roles:
Now, I cannot make the program run the text
function, and print test
, that is what I've sent from my phone. Also, the X-Forwarded-For
ip always changes. Why is that happening and how I can make the program run the test
function instead of the data
?
Here is my kotlin code if it works of something.
fun connect() {
val app: SocketInstance = application as SocketInstance
var mSocket = app.getMSocket()
//connecting socket
mSocket?.connect()
val options = IO.Options()
options.reconnection = true //reconnection
options.forceNew = true
progressBar2.setProgress(100, true)
if(mSocket?.connected()!!)
{
Toast.makeText(this,"Socket is connected",Toast.LENGTH_SHORT).show()
progressBar2.setProgress(100, true)
try{
mSocket.emit("data", "test")
} catch( e: Exception) {
Toast.makeText(this,"Error sending",Toast.LENGTH_SHORT).show()
Thread.sleep(1000)
progressBar2.setProgress(0, true)
}
} else {
Toast.makeText(this,"Socket is not connected",Toast.LENGTH_SHORT).show()
Thread.sleep(1000)
progressBar2.setProgress(100, true)
try{
mSocket.emit("text", "test")
Toast.makeText(this, "Sent", Toast.LENGTH_SHORT).show()
} catch( e: Exception) {
Toast.makeText(this, "Error sending", Toast.LENGTH_SHORT).show()
Thread.sleep(1000)
progressBar2.setProgress(0, true)
}
}
}
This always outputs not connected, but does not give errors when emitting events.
question from:
https://stackoverflow.com/questions/65647542/node-js-net-websocket-receiving-data-from-wrong-event