Skip to content

Nikko Lab 6 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ],
"no-unused-vars": [2, {"vars": "local", "args": "after-used"}]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
114 changes: 114 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@

# Created by https://www.gitignore.io/api/node,osx,windows

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env


### OSX ###
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/node,osx,windows
Empty file added .gulpfile
Empty file.
78 changes: 40 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
![cf](https://i.imgur.com/7v5ASc8.png) Lab 06: TCP Chat Server
======

## To Submit this Assignment
* Fork this repository
* Write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-brian`
* Push to your repository
* Submit a pull request to this repository
* Submit a link to your PR in canvas
* Write a question and observation on canvas

## Include
* `.gitignore`
* `.eslint`
* `package.json`
* `gulpfile.js`
* `README.md`
* write a paragraph about your project
* write documentation on how to get the project running
* write documentation on how to connect to the server

## Description

* Create a TCP Server using the NodeJS native `net` module
* Create a Client Constructor
* When sockets connect to the server, a new `Client` instance should be made
* All clients should have a unique `id` property - this should come from the use of `node-uuid`
* When sockets are connected with the client pool they should be given event listeners for `data`, `error`, and `close` events
* When a socket emits the `close` event, the socket should be removed from the client pool
* When a socket emits the `error` event, the error should be logged on the server
* When a socket emits the `data` event, the data should be logged on the server and the commands below should be implemented

## Custom commands
* `@all` should trigger a broadcast event
* `@nickname` should allow a user change their nickname
* `@dm` should allow a user to send a message directly to another user by nick name or by their guest id _(unique client id)_
* when a user sends a message, their nickname should be printed
* **i.e.** `cfcrew: sup chatterz`
# TCP Chat_Server

This app was built to host a small "chat room" using "TelNet." The host will first need to initialize the server. Upon doing so, the host may share their IP address to any users wishing to join the room.

#### Getting Started:
In order to begin using the app, navigate to the app's main directory in your terminal. Then run the following command:
```
node server.js
```
This will initiate the server for the chat room.

Then you must share your current IP address (found in your network settings) with any users wishing to join the chat server. Any user may join by typing this command into their terminal:

```
telnet [Host IP] 3000
```
In the case that the host has a specified PORT, let the command '3000' above be changed to the host's specified PORT number. [Host IP] is the IP address found in host's network settings.

#### Commands:
A user is able to make the following commands:
- '@all' (will message every user currently in the room).
- '@dm' [username] (will directly message a user where [username] is someone currently in the chat room.
- '*[nickname]' (will allow any user to change their publicly displaying nick name.
- '-help' (will print out all available commands).

**Note that when using @dm there is a space between [username] and the command. whereas with *[username]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an incomplete


#### Features:
-'help' command to print a list of viable commands to the user.
-The ability for each user to change their publicly displaying nickname.
-A dynamically updating 'pool' of users, which also displays the current amount.

#### Built Using:
-"Net" (node module)
-"Events" (node module)
-"Node-UUID" (npm)

#### Possible Future Features:
-A command to display every user currently in the pool (in order to message them directly).
-Have funny emotes print to the screen, i.e. shorthand commands.
9 changes: 9 additions & 0 deletions model/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';

const uuid = require('node-uuid');

const Client = module.exports = function(socket) {
this.id = uuid.v4();
this.nickName = `user_${Math.random()}`;
this.socket = socket;
};
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "06-tcp_servers",
"version": "1.0.0",
"description": "![cf](https://i.imgur.com/7v5ASc8.png) Lab 06: TCP Chat Server ======",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/npisciotti1/06-tcp_servers.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/npisciotti1/06-tcp_servers/issues"
},
"homepage": "https://github.com/npisciotti1/06-tcp_servers#readme",
"dependencies": {
"node-uuid": "^1.4.7"
}
}
101 changes: 101 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
'use strict';

const net = require('net');
const PORT = process.env.PORT || 3000;
const server = net.createServer();
const Client = require(`${__dirname}/model/client.js`);
const EE = require('events');
const ee = new EE();

const pool = [];

var userCount = 0;

//192.168.0.5.

server.listen(PORT, function() {
console.log('Port running on:', PORT);
});

function setGuestName(client) {
client.nickName = 'New_User ' + (userCount + 1);
userCount++;
}

server.on('connection', function(socket) {
var client = new Client(socket);
setGuestName(client);
pool.push(client);
console.log('User:', client.nickName, 'has joined the chat server!');
console.log('Users in Room:', pool.length);
console.log('Type: "-help", for help!');

socket.on('close', function() {
pool.forEach(function(c, idx) {
if(client.id === c.id) {
console.log(client.nickName, 'has left the chatroom.');
pool.splice(idx, 1);
return;
}
});
});

socket.on('data', function(data){
const command = data.toString().split(' ').shift().trim();
console.log(client.nickName + ': ' + data);

if(command.startsWith('*')) {
ee.emit('*', client, data);
return;
}
if(command.startsWith('-help')) {
ee.emit('-help', client, data);
return;
}
if(command.startsWith('@all')) {
ee.emit('@all', client, data);
return;
}
if(command.startsWith('@dm')) {
ee.emit('@dm', client, data);
return;
}
ee.emit('default', client, data);
});
});

ee.on('*', function(client, data) {
let nickname = data.toString().split('').slice(1).join('').trim();
console.log(nickname);
client.nickName = nickname;
});

ee.on('@dm', function(client, data) {
let recipient = data.toString().split(' ').slice(1, 2).join(' ').trim();
console.log('intended recipient:', recipient);
let message = data.toString().split(' ').slice(1).join(' ').trim();
pool.forEach(function(c) {
if (recipient === c.nickName) {
c.socket.write(client.nickName + message + '\n');
}
});
});

ee.on('@all', function(client, data) {
let message = data.toString().split(' ').slice(1).join(' ').trim();
pool.forEach(function(c) {
c.socket.write(client.nickName + message + '\n');
});
});

ee.on('-help', function() {
console.log('Here are the commands you may use:',
'*[yourName] <--- use as such to change your Public displying name ||',
'@dm [user] <--- use as such to message one user directly ||',
'@all <--- Will write a message to all users'
);
});

ee.on('default', function(client) {
client.socket.write('not a command\n');
});