引言:
上一篇文章中,我们学习了UDP协议,在传输层中,出了UDP之外,TCP协议也是经常被提起的,今天让我们写一个最简单的TCP服务端和客户端
UDP和TCP对比:
- 不可靠传输和可靠传输
- 无连接和有连接
- 面向数据流和面向字节流
- 在服务端方面:
- TCP要建立监听(listen)和接收链接(accept) 。
- 在客户端方面:
- 要接收链接(connect)
实现最简单的TCP服务端和客户端
服务端
#include<iostream>
#include<string>
#include<string.h>
#include<strings.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
using namespace std;
class TcpServer
{
private:
int listen_sock;
string ip;
int port;
public:
//构造
TcpServer(string _ip, int _port)
:listen_sock(-1),
ip(_ip),
port(_port)
{
}
//初始化
void InitServer()
{
//创建套接字
listen_sock = socket(AF_INET, SOCK_STREAM, 0);
if(listen_sock < 0)
{
cerr << "socker error" << endl;
exit(2);
}
//进行绑定
struct sockaddr_in local;
bzero(&local, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(port);
local