自己搭服务器,由于主机性能太差,运行Java环境太过于勉强,只能跑跑C++。正好顺带着参考网络资料,学习下Node.js。
最近传了两段代码,分别是C++和Node.js实现的Socket服务端
Linux C++ 实现的Server端博文:
http://blog.csdn.net/dreamstone_xiaoqw/article/details/77872075
Node 实现的Server端博文:
http://blog.csdn.net/dreamstone_xiaoqw/article/details/77910941
#include
#include /* See NOTES */
#include
#include
#include
#include
#include
#include
const int MAXLINE = 4096;
const int LISTENQ = 1024;
int main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
time_t ticks;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(8080);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, LISTENQ);
for ( ; ; ) {
len = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &len);
printf("connect from %s, port %d\n",
inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
ntohs(cliaddr.sin_port));
read(connfd, buff, strlen(buff));
printf("Recive msg: %s\n", buff);
bzero(buff, sizeof(buff));
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
write(connfd, buff, strlen(buff));
printf("Send msg: %s\n", buff);
close(connfd);
}
return 0;
}
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain});
response.end('Hello World\n');
}).listen(8080);
console.log('Server running at http://yixzm.cn:8080/');
可以看出,同样的功能,代码量差别真的很大。甚至Node.js还多了一个发送http头的功能。
但这也只是浮于表面的一点代码对比,更多的比较还需要继续不断的学习慢慢体会。