sockets(套接字)编程有三种,流式套接字(SOCK_STREAM),数据报套接字(SOCK_DGRAM),原始套接字(SOCK_RAW);
基于TCP的socket编程是采用的流式套接字。
第一式: 加载/释放Winsock库:
1.加载方法:
WSADATA wsa;
/*初始化socket资源*/
if (WSAStartup(MAKEWORD(1,1),&wsa) != 0)
{
return; //代表失败
}
2.释放方法:
WSACleanup();
第二式: 构造SOCKET:
1.服务端:构造监听SOCKET,流式SOCKET.
SOCKET Listen_Sock = socket(AF_INET, SOCK_STREAM, 0)
2.客户端:构造通讯SOCKET,流式SOCKET.
SOCKET Client_Sock = socket(AF_INET, SOCK_STREAM, 0)
第三式:配置监听地址和端口:
1.服务端: SOCKADDR_IN serverAddr
ZeroMemory((char *)&serverAddr,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(1234); /*本地监听端口:1234*/
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /*有IP*/
第四式: 绑定SOCKET:
1.服务端:绑定监听SOCKET.
bind(Listen_Sock,(struct sockaddr *)&serverAddr,sizeof(serverAddr))
第五式: 服务端/客户端连接:
1.服务端:等待客户端接入.
SOCKET Command_Sock = accept(Listen_Sock, ...)
2.客户端:请求与服务端连接.
int ret = connect(Client_Sock, ...)
第六式: 收/发数据:
1.服务端:等待客户端接入.char buf[1024].
接收数据:recv(Command_Sock,buf, ...)
或
发送数据:send(Command_Sock,buf, ...)
2.客户端:请求与服务端连接.char buf[1024].
发送数据:send(Client_Sock,buf, ...)
或
接收数据:recv(Client_Sock,buf, ...)
第七式: 关闭SOCKET:
1.服务端:关闭SOCKET.
closesocket(Listen_Sock)
closesocket(Command_Sock)
2.客户端:关闭SOCKET.
closesocket(Client_Sock)
1.Server.cpp
#include
#include
#pragma comment(lib,"WS2_32.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[50];
sprintf(sendBuf,"Welcome %s to here!",inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[50];
recv(sockConn,recvBuf,50,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
2.Client.cpp
#include
#include
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));
send(sockClient,"hello",strlen("hello")+1,0);
char recvBuf[50];
recv(sockClient,recvBuf,50,0);
printf("%s\n",recvBuf);
closesocket(sockClient);
WSACleanup();
}
引用博客:http://www.cnblogs.com/Sniper-quay/archive/2011/06/22/2086636.html