1.服务器端
#include "stdafx.h"
#include
using namespace std;
#include
#pragma comment(lib,"WS2_32.lib")
#define MAX_BUFFER 256 //对于收发的数据有限 有必要考虑封装数据收发函数
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2,2); //设置版本号
if(::WSAStartup(sockVersion,&wsaData)) //初始化网络资源
exit(0);
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, 0);
if(sock == SOCKET_ERROR)
{
cout<<"Fail socket()."< return 0;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(6000);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
if(::bind(sock,(SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //绑定
{
cout<<"Failed bind()."< return 0;
}
if(::listen(sock,5) == SOCKET_ERROR) //监听
{
cout<<"Failed listen()."< return 0;
}
sockaddr_in clientAddr;
SOCKET clientSock;
int len = sizeof(clientAddr);
char szTest[MAX_BUFFER]={0};
clientSock = ::accept(sock,(SOCKADDR*)&clientAddr,&len); //接受
if(clientSock == INVALID_SOCKET)
{
cout<<"Failed accept()!"< return 0;
}
else
{
cout<<"接受到一个连接: "< }
while(true)
{
cout<<"请输入数据: ";
cin>>szTest;
::send(clientSock, szTest, strlen(szTest),0);
char szBuf[256] = {0};
int len = ::recv(clientSock, szBuf,256,0);
if(len > 0)
{
szBuf[len] = 0;
cout<<"客户端说: "< }
Sleep(100);
}
::closesocket(clientSock);
::closesocket(sock); //关闭套接字
::WSACleanup(); //释放网络资源
getchar();
return 0;
}
//WSAStartup socket accept bing listen 等函数详见帮助文档
客户端:
#include "stdafx.h"
#include
using namespace std;
#include
#pragma comment(lib,"WS2_32.lib")
#define MAX_BUFFER 256
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2,2);
if(::WSAStartup(sockVersion,&wsaData))
exit(0);
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, 0);
if(sock == SOCKET_ERROR)
{
cout<<"Fail socket()."< return 0;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(6000);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if(::connect(sock,(SOCKADDR*)&addr, sizeof(addr)) == -1)
{
cout<<"Failed connect()!"< return 0;
}
char szTest[MAX_BUFFER]={0};
while(true)
{
char szBuf[256] = {0};
int len = ::recv(sock, szBuf,256,0);
if(len > 0)
{
szBuf[len] = 0;
cout<<"服务器说: "<
}
cout<<"请输入数据: ";
cin>>szTest;
::send(sock, szTest, strlen(szTest),0);
Sleep(100);
}
::closesocket(sock);
::WSACleanup();
getchar();
return 0;
}
由于:accept,recv,send等函数式阻塞式的,所指只能你一句,我一句那样通话