Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
N
nodeJS-presentation
Manage
Activity
Members
Labels
Plan
Issues
0
Issue boards
Milestones
Wiki
Code
Merge requests
0
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Model registry
Operate
Environments
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Stefan Dierauf
nodeJS-presentation
Commits
1667cf62
Commit
1667cf62
authored
10 years ago
by
Stefan Dierauf
Browse files
Options
Downloads
Patches
Plain Diff
added chatserver.js
parent
4b8b1a4c
No related branches found
Branches containing commit
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
slides/chatserver.js
+45
-0
45 additions, 0 deletions
slides/chatserver.js
with
45 additions
and
0 deletions
slides/chatserver.js
0 → 100644
+
45
−
0
View file @
1667cf62
// Load the TCP Library
net
=
require
(
'
net
'
);
// Keep track of the chat clients
var
clients
=
[];
// Start a TCP Server
net
.
createServer
(
function
(
socket
)
{
// Identify this client
socket
.
name
=
socket
.
remoteAddress
+
"
:
"
+
socket
.
remotePort
// Put this new client in the list
clients
.
push
(
socket
);
// Send a nice welcome message and announce
socket
.
write
(
"
Welcome
"
+
socket
.
name
+
"
\n
"
);
broadcast
(
socket
.
name
+
"
joined the chat
\n
"
,
socket
);
// Handle incoming messages from clients.
socket
.
on
(
'
data
'
,
function
(
data
)
{
broadcast
(
socket
.
name
+
"
>
"
+
data
,
socket
);
});
// Remove the client from the list when it leaves
socket
.
on
(
'
end
'
,
function
()
{
clients
.
splice
(
clients
.
indexOf
(
socket
),
1
);
broadcast
(
socket
.
name
+
"
left the chat.
\n
"
);
});
// Send a message to all clients
function
broadcast
(
message
,
sender
)
{
clients
.
forEach
(
function
(
client
)
{
// Don't want to send it to sender
if
(
client
===
sender
)
return
;
client
.
write
(
message
);
});
// Log it to the server output too
process
.
stdout
.
write
(
message
)
}
}).
listen
(
5000
);
// Put a friendly message on the terminal of the server.
console
.
log
(
"
Chat server running at port 5000
\n
"
);
\ No newline at end of file
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment