TCP阻塞套接字客户端和服务器
Server部分
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#include <Winsock.h>
#pragma comment(lib,"WS2_32.lib")
bool main()
{
DWORD dwVerHigh=2,dwVerLow=2;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(dwVerLow,dwVerHigh),&wsaData))
{
MessageBox(NULL,"Failed to Load The Lib","Failure",MB_OK);
return false;
}
SOCKET sListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sListen)
{
MessageBox(NULL,"Failed To Create Socket sListen","Failure",MB_OK);
return false;
}
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(4567);
sin.sin_addr.S_un.S_addr=INADDR_ANY;
if(SOCKET_ERROR==bind(sListen,(LPSOCKADDR)&sin,sizeof(sin)))
{
MessageBox(NULL,"Failed to Bind!","Failure",MB_OK);
return false;
}
if(SOCKET_ERROR==listen(sListen,5))
{
MessageBox(NULL,"Failed to Listen","Failure",MB_OK);
return false;
}
sockaddr_in remoteAddr;
int nAddrLen=sizeof(remoteAddr);
SOCKET sClient;
char *pszBuffer="Hello!";
while(true)
{
sClient=accept(sListen,(SOCKADDR*)&remoteAddr,&nAddrLen);
if(INVALID_SOCKET==sClient)
{
cout<<"Failed to Accept!"<<endl;
continue ;
}
cout<<"Get a remoteAddr!"<<endl;
send(sClient,pszBuffer,strlen(pszBuffer)+1,0);
closesocket(sClient);
}
closesocket(sListen);
return true;
}
******************************************************************************
Client部分
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#include <Winsock.h>
#pragma comment(lib,"WS2_32.lib")
bool main()
{
DWORD dwVerHigh=2,dwVerLow=2;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(dwVerLow,dwVerHigh),&wsaData))
{
MessageBox(NULL,"Failed to Load The Lib","Failure",MB_OK);
return false;
}
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==s)
{
MessageBox(NULL,"Failed to Create Socket!","Failure",MB_OK);
return false;
}
sockaddr_in servAddr;
servAddr.sin_family=AF_INET;
servAddr.sin_port=htons(4567);
servAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
if(-1==connect(s,(sockaddr*)&servAddr,sizeof(servAddr)))
{
MessageBox(NULL,"Failed to Connect","Failure",MB_OK);
return false;
}
while(true)
{
char szBuffer[256];
int nRecv=recv(s,szBuffer,256,0);
if(nRecv>0)
{
cout<<szBuffer<<endl;
}
}
closesocket(s);
return true;
}