简单封装 并不实际应用
框架图
Mysocket 主要是定义TCP和UDP的一些相同的操作,需要的他们各自去实现。
Mysocket.h
#ifndef MYSOCKET_H
#define MYSOCKET_H
class MySocket
{
public:
MySocket();
~MySocket();
// 创建一个套接字
virtual int Create(){};
// IO操作
virtual int Send(){};
virtual int Recvice(){};
// 关闭
virtual void Close(){};
};
MySocket::MySocket()
{
}
MySocket::~MySocket()
{
}
#endif // !MYSOCKET
TcpSocket 首先实现一些客户端和服务端公用的接口,然后利用虚函数定义一些他们各自需要实现的接口。
TcpSocket.h
#ifndef TCPSOCKET_H
#define TCPSOCKET_H
#include <sys/types.h>
#include <sys/socket.h>
#include "MySocket.h"
#include <stdlib.h>
class TcpSocket
: public MySocket
{
public:
TcpSocket();
~TcpSocket();
// 重写覆盖
int Create() override;
int Send() override;
int Recvice() override;
void Close() override;
// server端操作
virtual int Bind(char *IP,int PORT){};
virtual int Listen(){};
virtual int Accept(){};
// client操作
virtual int Connect(char *IP,int PORT){};
int fd; // socket描述符
int fd1; // aceept接受描述符
char rbuf[1024];
char sbuf[1024];
};
#endif // !TCPSOCKET_H
TcpSocket.cpp
#include "TcpSocket.h"
#include <iostream>
#include <unistd.h>
using namespace std;
TcpSocket::TcpSocket()
{
}
TcpSocket::~TcpSocket()
{
Close();
}
int TcpSocket::Create()
{
int f = socket(AF_INET, SOCK_STREAM, 0);
if(f != -1){
cout << "socke创建成功:" << f << endl;
}
return f;
}
int TcpSocket::Send()
{
write(fd, sbuf, sizeof(sbuf) - 1);
return 0;
}
int TcpSocket::Recvice()
{
int s = read(fd1, rbuf, sizeof(rbuf) - 1);
if(s > 0){
cout << "client:" << rbuf << endl;
}
// if(s == -1){
// // cout << "连接中断" << endl;
// break;
// }
return s;
}
void TcpSocket::Close()
{
shutdown(fd, 2);
shutdown(fd1, 2);
}
TcpServerSocket实现服务端特有的功能
TcpServerSocket.h
#ifndef TCPSERVERSOCKET_H
#define TCPSERVERSOCKET_H
#include <sys/types.h>
#include <sys/socket.h>
#include "TcpSocket.h"
class TcpServerSocket : public TcpSocket
{
public: