一个简单的基于node.js的TCP服务器和基于C++的TCP客户端通信示例程序

var net=require("net");
var serverIP="127.0.0.1";
var serverPort=10553;

var server=net.createServer(function(sock){
    console.log("Accepting connection: " + sock.remoteAddress + ":" + sock.remotePort );
    
    sock.write("Login server based on Node.js success!");
    
    sock.on("data",function(data){
        console.log(sock.remoteAddress + ":" + sock.remotePort + " -> " + data);
        
        sock.write('Node.js server received data"' + data + '"');
    });
    
    /*客户端调用closesocket或强制关闭时会导致服务器端会发射"close"事件,但是它发生在"error"事件之后。
    sock.remoteAddress和sock.remotePort是undefined.*/
    sock.on("close",function(data){
        console.log(sock.remoteAddress + ":" + sock.remotePort + " logout!");
    });
    
    /*必须监听一个“error”事件,否则在客户端调用closesocket或强制关闭时服务器端会发射“error"事件。
    如果没有该事件的处理程序,进程便会异常终止。*/
    sock.on("error",function(error,data){
        if(error)
        {
            console.log("Occurs an error: " + error);
        }
    });
});
server.listen(serverPort,serverIP);
console.log("server listening at " + serverIP + ":" + serverPort);
console.log("Waiting connection ... ...");

以下是C++客户端程序的示例代码:

#include <winsock2.h>
#pragma comment (lib,"Ws2_32.lib")
#include <windows.h>
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::cerr;
using std::string;

bool InitSocketLibrary(void)
{
	WORD wVersionRequested;
	WSADATA wsaData;
	
	wVersionRequested = MAKEWORD(2,2);

	int err =WSAStartup(wVersionRequested,&wsaData);
	if ( err != 0 )
	{
		return false;
	}
	if(LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2)
	{
		WSACleanup();
		return false;
	}

	return true;
}
int main()
{
	if(!InitSocketLibrary())
	{
		cerr << "Fail to initialize WinSock!" << endl;
		return -1;
	}

	SOCKET sock=socket(AF_INET,SOCK_STREAM,0);

	SOCKADDR_IN addrBind;
	addrBind.sin_family=AF_INET;
	addrBind.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
	addrBind.sin_port=htons(0);
	int nRet=bind(sock,(SOCKADDR*)&addrBind,sizeof(SOCKADDR_IN));
	if(nRet==SOCKET_ERROR)
	{
		cerr << "Error,fail to bind socket:" << WSAGetLastError() << endl;
	}

	SOCKADDR_IN addrSrv;
	addrSrv.sin_family=AF_INET;
	addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	addrSrv.sin_port=htons(10553);

	nRet=connect(sock,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR_IN));
	if(nRet==SOCKET_ERROR)
	{
		cout << "Fail to connection server!" << endl;
		return 0;
	}

	char recvBuf[100]={0};
	nRet=recv(sock,recvBuf,100,0);
	if(nRet>0)
	{
		recvBuf[nRet]=0;
		cout << recvBuf << endl;

		cout << "input something to send('#'to quit): ";

		string strContent;
		while(true)
		{
			getline(cin,strContent);
			if(strContent.at(0)=='#')
				break;
			send(sock,strContent.c_str(),strContent.length(),0);
		}
		

		closesocket(sock);
		WSACleanup();
	}
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值