本程序仅仅是为了演示基于TCP协议TCP协议的网络通信程序的写法采用阻塞模式代码简单
服务器端代码
#include Winsockh
#include stdioh
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD();
err = WSAStartup( wVersionRequested &wsaData );
if ( err != )
{
return;
}
if ( LOBYTE( wsaDatawVersion ) != ||
HIBYTE( wsaDatawVersion ) != )
{
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INETSOCK_STREAM);
SOCKADDR_IN addrSrv;
addrSrvsin_addrS_unS_addr=htonl(INADDR_ANY);
addrSrvsin_family=AF_INET;
addrSrvsin_port=htons();
bind(sockSrv(SOCKADDR*)&addrSrvsizeof(SOCKADDR));
listen(sockSrv);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while()
{
SOCKET sockConn=accept(sockSrv(SOCKADDR*)&addrClient&len);
char sendBuf[];
sprintf(sendBufWelcom %s to inet_ntoa(addrClientsin_addr));
send(sockConnsendBufstrlen(sendBuf)+);
char recvBuf[];
recv(sockConnrecvBufstrlen(recvBuf));
printf(%s\nrecvBuf);
closesocket(sockConn);
}
}
『注意』本程序使用了动态连接库文件Ws_lib需要在工程属性里添加对Ws_lib的连接本程序用VC编译添加方法是在project\Configuration properties\Linker\Input下的Additional Dependencies 项里写如Ws_lib
客户端代码
#include Winsockh
#include stdioh
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD();
err = WSAStartup( wVersionRequested &wsaData );
if ( err != )
{
return;
}
if ( LOBYTE( wsaDatawVersion ) != ||
HIBYTE( wsaDatawVersion ) != )
{
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INETSOCK_STREAM);
SOCKADDR_IN addrSrv;
addrSrvsin_addrS_unS_addr=inet_addr(); //是
一个回路地址
addrSrvsin_family=AF_INET;
addrSrvsin_port=htons();
connect(sockClient(SOCKADDR*)&addrSrvsizeof(SOCKADDR));
char recvBuf[];
recv(sockClientrecvBufstrlen(recvBuf));
printf(%s\nrecvBuf);
send(sockClient我是胡林strlen(我是胡林)+);
closesocket(sockClient);
WSACleanup();
}
同服务器端一样客户端程序也使用了Ws_lib动态连接库需要在工程属性里添加对Ws_lib的连接