服务端
#include <Winsock2.h>
#include <stdio.h>
voidmain(){
//加载嵌套字库
WORDwVersionRequested;
WSADATA wsaData;
interr;
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_family=AF_INET;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_port=htons(6000);
//绑定嵌套字
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
//将嵌套字设为监听模式
listen(sockSrv,5);
SOCKADDR_IN addrClient;
intlen=sizeof(SOCKADDR);
while(1){
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
charsendBuf[100];
sprintf_s(sendBuf,"Welcome %s to MFC",inet_ntoa(addrClient.sin_addr));
//发送数据
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
charrevBuf[100];
//接受数据
recv(sockConn,revBuf,100,0);
//打印数据
printf("%s\n",revBuf);
//关闭嵌套字
closesocket(sockConn);
}
}
客户端
#include <Winsock2.h>
#include <stdio.h>
voidmain(){
//加载嵌套字库
WORDwVersionRequested;
WSADATA wsaData;
interr;
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_family=AF_INET;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_port=htons(6000);
//向服务器发送请求
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
//接收数据
charrecvBuf[100];
recv(sockClient,recvBuf,100,0);
printf("%s\n",recvBuf);
send(sockClient,"This is lisi",strlen("This is lisi")+1,0);
closesocket(sockClient);
WSACleanup();
}