This commit is contained in:
azw 2023-04-22 09:44:29 +00:00
parent 736500c141
commit cfdeca99ac
2 changed files with 55 additions and 0 deletions

View File

@ -1,5 +1,8 @@
#include <a8/a8.h>
#include <memory.h>
#include <unistd.h>
#include <a8/udpsession.h>
static const int DEFAULT_MAX_PACKET_LEN = 1024 * 10;
@ -28,4 +31,44 @@ namespace a8
max_packet_len_ = std::max(max_packet_len, DEFAULT_MAX_PACKET_LEN);
}
void UdpSession::OnSocketRead(char* buf, unsigned int buflen)
{
unsigned int already_read_bytes = 0;
do {
if (already_read_bytes < buflen) {
int read_bytes = std::min(buflen - already_read_bytes,
(unsigned int)max_packet_len_ - recv_bufflen_);
if (read_bytes > 0) {
memmove(&recv_buff_[recv_bufflen_], buf + already_read_bytes, read_bytes);
recv_bufflen_ += read_bytes;
already_read_bytes += read_bytes;
}
}
int offset = 0;
int prev_offset = 0;
do {
prev_offset = offset;
DecodePacket(recv_buff_, offset, recv_bufflen_);
} while (prev_offset < offset && offset < recv_bufflen_);
if (offset > 0 && offset < recv_bufflen_){
memmove(recv_buff_, recv_buff_ + offset, recv_bufflen_ - offset);
}
recv_bufflen_ -= offset;
if (recv_bufflen_ >= max_packet_len_) {
//收到超长包
#if 0
Close();
#endif
return;
}
} while (already_read_bytes < buflen);
}
void UdpSession::DecodePacket(char* buf, int& offset, unsigned int buflen)
{
DecodeUserPacket(buf, offset, buflen);
}
}

View File

@ -1,5 +1,10 @@
#pragma once
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>
namespace a8
{
@ -13,6 +18,13 @@ namespace a8
void Update();
void SetMaxPacketLen(int max_packet_len);
virtual void OnRecvPacket() = 0;
virtual void SendClientMsg(char* buf, int buf_len) = 0;
protected:
virtual void OnSocketRead(char* buf, unsigned int buflen);
virtual void DecodePacket(char* buf, int& offset, unsigned int buflen);
virtual void DecodeUserPacket(char* buf, int& offset, unsigned int buflen) = 0;
private:
a8::UdpListener* listener_ = nullptr;