标签:sock
服务端代码
void TCPServer()
{
//创建服务器socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socketServer)
{
return;
}
//绑定IP和端口
struct sockaddr_in serverAddr = {0};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(5780);
serverAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//绑定本机所有IP
bind(socketServer,(struct sockaddr*)&serverAddr, sizeof(serverAddr));
//侦听
listen(socketServer, SOMAXCONN);
printf("等候客户端链接。。。。。\n");
//等候客户端
struct sockaddr_in clientAddr = {0};
int nLen = sizeof(clientAddr);
SOCKET sockClient = accept(socketServer, (sockaddr*)&clientAddr,&nLen);//阻塞函数 等候客户端的链接并返回链接好的 套接字
//数据收发
printf("客户端已经链接。。。。。\n");
char szText[100] = { 0 };
recv(sockClient, szText, 100, 0);//阻塞函数
printf("%s", szText);
char szSend[100] = "Hello 我是服务器";
send(sockClient, szSend, sizeof(szSend), 0);
_getch();
//关闭socket
closesocket(sockClient);
closesocket(socketServer);
}
客户端代码:
void TCPClient()
{
//////////////////////////////////////////////////////////////////////////
//创建socket
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == sockClient)
{
return;
}
//链接到服务器
struct sockaddr_in addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_port = htons(5780);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//当前机器的IP地址
connect(sockClient, (struct sockaddr*)&addr, sizeof(addr));//需要指定链接的服务器的IP地址 和端口
//数据的收发
printf("链接服务器。。。。。\n");
char szSend[100] = "Hello 我是客户端";
send(sockClient, szSend, sizeof(szSend), 0);
char szRecv[100] = { 0 };
recv(sockClient, szRecv, sizeof(szRecv), 0);
printf("%s", szRecv);
getch();
//关闭socket
closesocket(sockClient);
}
标签:sock
原文地址:http://blog.csdn.net/djb100316878/article/details/46490521