Skip to content

lab-regan #12

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 2 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
19 changes: 19 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ]
},
"env": {
"es6": true,
"node": true,
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
129 changes: 129 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

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

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### 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/osx,node,linux,windows
46 changes: 13 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,18 @@
![cf](https://i.imgur.com/7v5ASc8.png) Lab 06: TCP Chat Server
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
This is a basic TCP chat server built with Node.js. All logic is built into the main file while user data is abstracted into a separate model. It relies on node's native uuid module to create user ids as well as node's native net module to create and run the server.

## 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
## To get it started:
Clone the repo and import Node's uuid module by using ```npm i node-uuid```
Then open the application using 'node server'
Anyone wishing to communicate with others using this app should first identify their IP address and then, in a separate command line window from the server, input 'telnet 000.000.0.0 3000'
where '000.000.0.0' should be the desired IP and '3000' should be whatever port you wish to use.
From there the app will run and you can reference the custom commands below to create a personalized experience.

## 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`
`@all` will trigger a broadcast event
`@nickname` will allow a user change their nickname
`@dm` will allow a user to send a message directly to another user by their nickname or by their guest id _(unique client id)_
when a user sends a message, their nickname will be printed
**i.e.** `chattyCathy: sup chatterz`
13 changes: 13 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');

gulp.task('lint', function(){
return gulp.src(['**/*.js', '!node_modules'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});

gulp.task('default', ['lint']);
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.socket = socket;
this.nickname = `user_${Math.random()}`;
this.id = uuid.v4();
};
27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "lab-regan",
"version": "1.0.0",
"description": "![cf](https://i.imgur.com/7v5ASc8.png) Lab 06: TCP Chat Server ======",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/reganoneill/06-tcp_servers.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/reganoneill/06-tcp_servers/issues"
},
"homepage": "https://github.com/reganoneill/06-tcp_servers#readme",
"dependencies": {
"node-uuid": "^1.4.7"
},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1"
}
}
84 changes: 84 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
'use strict';

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

const pool = [];

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

ee.on('@dm', function(client, string){
let message = string.split(' ').slice(1).join(' ').trim();
let callByName = string.split(' ').shift().trim();
pool.forEach(c => {
console.log('nickname:', c.nickname);
console.log('id:', c.id);
if(c.nickname === callByName || c.id === callByName){
c.socket.write(`${client.nickname} says: ${message}`);
Copy link

@jalleng jalleng Feb 21, 2017

Choose a reason for hiding this comment

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

You should add a new line character (\n) here after the message so their cursor will drop down to the next line.

}
});
});

ee.on('@all', function(client, string){
pool.forEach(c => {
c.socket.write(`${client.nickname}: ${string}`);
});
client.socket.write(`did you really need to put that on blast, ${client.nickname}?\n`);
});

ee.on('@nickname', function(client, string){
let nickname = string.split(' ').shift().trim();
console.log('new nickname:', nickname);
client.nickname = nickname;
pool.forEach(c => {
console.log('nickname: ', c.nickname);
});
});

ee.on('leftChat', function(client){
console.log(`pool had ${pool.length} chatters`);
console.log(client.nickname + ' has left the chat');
pool.forEach( c => {
if(c.nickname === client.nickname){
let index = pool.indexOf(c.nickname);
pool.splice(index, 1);
console.log(`pool now has ${pool.length} chatters`);
return;
}
});
});

server.on('connection', function(socket){
var client = new Client(socket);
pool.push(client);

socket.on('data', function(data){
const command = data.toString().split(' ').shift().trim();
//this logs the data (part of it) to the server
console.log(`${client.nickname}, who has user-id:(${client.id}) used the command:`, command);
if(command.startsWith('@')){
ee.emit(command, client, data.toString().split(' ').slice(1).join(' '));
return;
}
ee.emit('default', client, data.toString());
});

socket.on('close', function(){
ee.emit('leftChat', client);
});

socket.on('error', function(err){
console.err(err);
});

});

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