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();
}
}