I'm trying to create a basic game (only text) using Node.js, and it's 'net' library.
I'm hitting a bit of a wall. I can't seem to figure out how to prompt the user to enter some information, and wait for the user to enter said information.
Here's the code I have so far. It's fairly basic, and will print out 2 lines for you when you run the client, and then hang. It's at that point I want the user to be able to enter information. I'm unsure of a few things here:
1. How do I enable the user to type? (more specifically, is it client or server side)
2. How do I send that data to the server when enter is pressed?
I have read up on some documentation as far as Telnet goes, and it leads me to my last question: is the Telnet module in Node really the right one for this, or is there a better alternative for client/server creation and communication?
Client Code:
var connect = require('net');
var client = connect.connect('80', 'localhost');
console.log('Connection Success!\n\n');
client.on('data', function(data) {
// Log the response from the HTTP server.
console.log('' + data);
}).on('connect', function() {
// Manually write an HTTP request.
//I'm assuming I could send data at this point here, on connect?
}).on('end', function() {
console.log('Disconnected');
});
Server Code:
var net = require('net');
var sockets = [];
function cleanInput(data) {
return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}
function receiveData(socket, data) {
var cleanData = cleanInput(data);
if(cleanData === "quit") {
socket.end('Goodbye!\n');
}
else {
for(var i = 0; i<sockets.length; i++) {
if (sockets[i] !== socket) {
sockets[i].write(data);
}
}
}
}
function closeSocket(socket) {
var i = sockets.indexOf(socket);
if (i != -1) {
sockets.splice(i, 1);
}
}
function newSocket(socket) {
sockets.push(socket);
socket.write('Welcome to the Battleship Server!\n\n');
socket.write('Please enter a username: ');
socket.on('data', function(data) {
receiveData(socket, data);
})
socket.on('end', function() {
closeSocket(socket);
})
}
var server = net.createServer(newSocket);
server.listen(80);
Thanks in advance!
process.stdin
and process.stdout
to interact with input/output from/to the terminal. Have a look here.process.stdin.once('data', function(data){ /* ... */ })
. The .once
method ensures that the callback is called just once when the user hits enter.The client code should look like:
var connect = require('net');
var client = connect.connect('80', 'localhost');
client.on('data', function(data) {
console.log('' + data);
process.stdin.once('data', function (chunk) {
client.write(chunk.toString());
});
}).on('connect', function() {
client.write('Hello');
}).on('end', function() {
console.log('Disconnected');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With