博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
TCP Socket Programming in Node.js
阅读量:5303 次
发布时间:2019-06-14

本文共 4172 字,大约阅读时间需要 13 分钟。

Programming TCP Sockets in Node.js

 

Eager to know how sockets are programmed in Node? There are three variants of sockets in Node - i. TCP, ii. UDP, iii. UNIX domain. In this particular post, I will show you the basics of TCP socket programming in Node.js.

There are two categories of TCP socket programs you can write - i. server, ii. client. A TCP server listens for connections to it from clients and send data to the client. A TCP client connects to a TCP server exchange data with it. The communication between client and server happens via sockets.

Programming TCP sockets in Node requires the net module, which is an asynchronous wrapper for network programming. The net module is capable of many things, but for today we'll just focus on creating a TCP server and a client.

Writing a TCP Server

Here is an example of a very simple TCP server written in Node. Read the comments thoroughly, it explains how the code works.

var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; // Create a server instance, and chain the listen function to it // The function passed to net.createServer() becomes the event handler for the 'connection' event // The sock object the callback function receives UNIQUE for each connection net.createServer(function(sock) { // We have a connection - a socket object is assigned to the connection automatically console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); // Add a 'data' event handler to this instance of socket sock.on('data', function(data) { console.log('DATA ' + sock.remoteAddress + ': ' + data); // Write the data back to the socket, the client will receive it as data from the server sock.write('You said "' + data + '"'); }); // Add a 'close' event handler to this instance of socket sock.on('close', function(data) { console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort); }); }).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);

The same thing can be accomplished in a slightly different way. Make sure to include the necessary variables from the last example for this one to work.

var server = net.createServer(); server.listen(PORT, HOST); console.log('Server listening on ' + server.address().address +':'+ server.address().port); server.on('connection', function(sock) { console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); // other stuff is the same from here });

So what's the difference? Basically they are the same thing, it's just we used different conventions of the JavaScript language. In the first example, we passed the connection event handler to net.createServer(), and chained the listen() function. In the latter, we took a more 'conventional' approach. Either way works.

Writing a TCP Client

Now let's write a client to connect to the server we created. The following code creates a simple client which connects to the server, sends a message to server, and disconnects after getting a response from the server. Read the comments to follow the code.

var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; var client = new net.Socket(); client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client client.write('I am Chuck Norris!'); }); // Add a 'data' event handler for the client socket // data is what the server sent to this socket client.on('data', function(data) { console.log('DATA: ' + data); // Close the client socket completely client.destroy(); }); // Add a 'close' event handler for the client socket client.on('close', function() { console.log('Connection closed'); });

So that's the very basics of TCP socket programming in Node.js, hope it helped you understand socket programming in Node better. Note that socket programming is a lot more than these simple examples. Once you start exchanging huge chunks of data and want to do complex things you will need to understand and use Streams and Buffers among other things.

Further Reading

转载于:https://www.cnblogs.com/oxspirt/p/10339111.html

你可能感兴趣的文章
拦截器
查看>>
Unity 3(二):Unity在AOP方面的应用
查看>>
java执行命令行
查看>>
在UGUI上显示3D模型,并限制范围的拖拽
查看>>
android TranslateAnimation 顶部segment分段移动动画
查看>>
搞站思路 <陆续完善中>
查看>>
T-SQL查询进阶--理解SQL Server中索引的概念,原理以及其他
查看>>
最短路算法笔记
查看>>
MySQL数据库重要知识点
查看>>
笔记本共享无线上网
查看>>
跨域请求的常用方式及解释
查看>>
hdu 1568 Fibonacci
查看>>
cocos2dx-js 的配置和安装
查看>>
python learning OOP1.py
查看>>
sql语句注意事项
查看>>
[转]如何把别人项目代码修改后 提交到github
查看>>
通俗理解docker
查看>>
Redis发布订阅和应用场景
查看>>
微软BI 之SSAS 系列 - 多维数据集中度量值设计时的聚合函数 (累加性_半累加性和非累加性)...
查看>>
thinkphp5的控制器调用自身模块和调用其他模块的方法
查看>>