一服务器端程序:
#include <winsock2.h>
#include <stdio.h>
void main()
{
//加载套接字
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);//获得sokect版本号
err=WSAStartup(wVersionRequested,&wsaData);//加载套接字库
if (0!=err)
{
return;
}
if (LOBYTE(wsaData.wVersion)!=1|| //判断当前的socket版本号是否是1.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,"welcome %s to http://www.sunxin.org",
inet_ntoa(addrClient.sin_addr));
//发送数据
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
//接收数据
recv(sockConn,recvBuf,100,0);
printf("%s/n",recvBuf);
//关闭套接字
closesocket(sockConn);
}
}
二。客户端程序
#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");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
char recvBuf[100];
recv(sockClient,recvBuf,100,0);
printf("%s/n",recvBuf);
send(sockClient,"123",strlen("123")+1,0);
closesocket(sockClient);
WSACleanup();
}
先运行服务器端,再运行客户端