TCP网络通信流程:
1.创建套接字(socket) — 买手机
2.为套接字绑定地址信息(bind) — 插卡
3.服务端开始监听(listen) — 待机
4.客户端请求连接(connect) — 打电话
5.服务端获取连接请求(accept) — 接电话
6.发送数据(send)
7.接收数据(recv)
8.关闭套接字(close) — 先挂电话后关机
头文件:
#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using std::cout;
using std::endl;
using std::cin;
using std::string;
inline void CHECK(bool operation) {
if (operation == false) {
exit(-1);
}
}
class TcpSocket {
public:
TcpSocket() : _sock(-1) {
}
void setNewSockFd(int newsockfd) {
_sock = newsockfd;
}
// 创建套接字
bool Socket() {
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock < 0) {
perror("socket error");
return false;
}
return true;
}
// 为套接字绑定地址信息
bool Bind(string& ip, uint16_t& port) const {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str