本程序仅仅是为了演示基于TCP协议的网络通信程序的写法,采用阻塞模式,代码简单:
服务器端代码:
#include "Winsock2.h"
#include "stdio.h"
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1,1);
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
char sendBuf[100];
sprintf(sendBuf,"Welcom %s to http://blog.hulin0229.com", inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
recv(sockConn,recvBuf,strlen(recvBuf),0);
printf("%s/n",recvBuf);
closesocket(sockConn);
}
}
『注意』本程序使用了动态连接库文件Ws2_32.lib,需要在工程属性里添加对Ws2_32.lib的连接。本程序用VC2005编译,添加方法是:在project/Configuration properties/Linker/Input下的Additional Dependencies 项里写如Ws2_32.lib
客户端代码:
#include "Winsock2.h"
#include "stdio.h"
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1,1);
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); //127.0.0.1是一个回路地址。
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
char recvBuf[100];
recv(sockClient,recvBuf,strlen(recvBuf),0);
printf("%s/n",recvBuf);
send(sockClient,"我是胡林",strlen("我是胡林")+1,0);
closesocket(sockClient);
WSACleanup();
}
同服务器端一样,客户端程序也使用了Ws2_32.lib动态连接库,需要在工程属性里添加对Ws2_32.lib的连接。