视频链接
三、示例程序
1.服务端
#include <iostream>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <string>
int main()
{
// 1.创建socket
int sockfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
printf("create socket error: errno=%d errmsg=%s\n", errno, strerror(errno));
return 1;
}
else
{
printf("create socket success\n");
}
// 2.绑定socket
std::string ip = "127.0.0.1";
int port = 8080;
struct sockaddr_in sockaddr;
std::memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(ip.c_str());
sockaddr.sin_port = htons(port);
if (::bind(sockfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0)
{
printf("socket bind error: errno=%d errmsg=%s\n", errno, strerror(errno));
return 1;
}else
{
printf("socket bind success: ip=%s port=%d\n", ip.c_str(), port);
}
// 3.监听socket
if (::listen(sockfd, 1024) < 0)
{
printf("socket listen error: errno=%d errmsg=%s\n", errno, strerror(errno));
}
else
{
printf("socket listening ...\n");
}
// 4.接受客户端连接
for (;;)
{
int connfd = ::accept(sockfd, nullptr, nullptr);
if (connfd < 0)
{
printf("socket accept error: errno=%d errmsg=%s\n", errno, strerror(errno));
return 1;
}
char buf[1024] = {0};
// 5.接收客户端的数据
size_t len = ::recv(connfd, buf, sizeof(buf), 0);
printf("recv: connfd=%d message=%s", connfd, buf);
// 6.向客户端发送数据
::send(connfd, buf, len, 0);
}
// 7.关闭socket
::close(sockfd);
}
2.客户端
#include <iostream>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <string>
int main()
{
//1.创建socket
int sockfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
printf("socket create error: errno=%d errmsg=%s\n", errno, strerror(errno));
return 1;
}
else
{
printf("socket create success\n");
}
//2.绑定socket
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (::connect(sockfd, (sockaddr *) &addr, sizeof(addr)) < 0)
{
printf("socket connect error: errno=%d errmsg=%s\n", errno, strerror(errno));
return 1;
}
//3.发送数据
std::string data = "hello world";
::send(sockfd, data.c_str(), data.size(),0);
//4.接收数据
char buf[1024] = {0};
::recv(sockfd, buf, sizeof(buf), 0);
printf("recv: message=%s\n", buf);
//5.关闭socket
::close(sockfd);
return 0;
}
四、socket封装