服务器端程序:
#include <Winsock2.h>
#include <stdio.h>
#pragma comment( lib, "Wsock32.lib" ) //加入lib库
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,"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
",recvBuf );
//关闭套接字
closesocket( sockConn );
}
}
客户端程序:
#include <Winsock2.h>
#include <stdio.h>
#pragma comment( lib, "Wsock32.lib" ) //加入lib库
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
",recvBuf );
//发送数据
send( sockClient,"This is lisi",strlen( "This is lisi" )+1,0 );
//关闭套接字
closesocket( sockClient );
WSACleanup();
}
先启动服务器端程序,在运行客户端程序。连接之后接收服务器发来的欢迎信息,在发给位于本机6000端口的服务器程序一条信息“This is lisi”。