Skip to content

Instantly share code, notes, and snippets.

@itsgreggreg
Last active February 23, 2021 14:15
Show Gist options
  • Save itsgreggreg/0e172cd631ab75a2ad74 to your computer and use it in GitHub Desktop.
Save itsgreggreg/0e172cd631ab75a2ad74 to your computer and use it in GitHub Desktop.
Simple TCP 1 to 1 chat in Node

Simple TCP 1 to 1 chat on Node

Can be used to establish a 1 to 1 chat across any TCP network with static IP addresses, such as a LAN or WAN.

Usage

Open a terminal

  • Start the server
  • node --harmony tcp-chat-server.js
  • Give it your name
  • Wait for a connection
  • Start chatting

In another termal

  • Start the client
  • node --harmony tcp-chat-client.js
  • Give it your name
  • Start chatting

Options

Server

A port can be specified as the first command line argument:
node --harmony tcp-chat-server.js 3000

Client

An IP address can be specified on the client as the first command line argument:
node --harmony tcp-chat-client.js 192.168.1.11

A port can be specified on the client as the second command line argument, but if so an IP must be specified:
node --harmony tcp-chat-client.js 192.168.1.11 3000

'use strict';
let
net = require('net'),
readline = require('readline'),
host = process.argv[2] || 'localhost',
port = process.argv[3] || 5000,
client = null,
myNick = null;
function startClient(){
client = net.connect({port: port, host: host}, function(){
client.write("Hello, I'm "+ myNick);
});
client.on('data', function(data){
data = data.toString();
console.log(data);
});
client.on('end', function(){
console.log('Server has disconnected.');
process.exit();
});
}
function getNick(){
console.log("What's your name?");
}
readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('line', function(line){
if(!myNick){
line = line.trim();
if(line.length < 1){
getNick();
} else {
myNick = line;
startClient();
}
} else {
client.write(myNick + ": " + line);
}
});
getNick();
'use strict';
let
net = require('net'),
readline = require('readline'),
port = process.argv[2] || 5000,
socket = null,
myNick = null;
function startServer(){
net.createServer(function (s) {
if(socket) return s.end("Sorry this chat is full");
socket = s;
socket.write("Welcome to the chat, I'm " + myNick);
socket.on('data', function (data) {
data = data.toString();
console.log(data);
});
socket.on('end', function(){
console.log('Client has disconnected');
socket = null;
});
}).listen(port);
console.log("Chat server running at port "+port);
}
function getNick(){
console.log("What's your name?");
}
readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('line', function(line){
if(!myNick){
line = line.trim();
if(line.length < 1){
getNick();
} else {
myNick = line;
startServer();
}
} else {
socket.write(myNick + ": " + line);
}
});
;
getNick();
@NotNikita
Copy link

Thanks, bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment