开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
标签 (4)
master
om_2016_08_05
om_2016_07_21_ref_gc
om_2016_06_15
om_2015_12_04_1
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
项目仓库所选许可证以仓库主分支所使用许可证为准
master
分支 (1)
标签 (4)
master
om_2016_08_05
om_2016_07_21_ref_gc
om_2016_06_15
om_2015_12_04_1
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
标签 (4)
master
om_2016_08_05
om_2016_07_21_ref_gc
om_2016_06_15
om_2015_12_04_1
lua_learn
/
src
/
cpp
/
main.cpp
lua_learn
/
src
/
cpp
/
main.cpp
main.cpp 23.81 KB
一键复制 编辑 原始数据 按行查看 历史
onemore 提交于 2017年01月08日 17:37 +08:00 . 完善样例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<stdint.h>
#include<assert.h>
#include <fcntl.h>
#ifdef WIN32
#include <ws2tcpip.h>
#include <mstcpip.h>
//#include <winsock.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib") // 不然链接出错
#include <windows.h>
#else
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
// 输出log
namespace {
class LogAddEnd
{
public:
void operator=(std::ostream& other)
{
other << std::endl;
}
};
#define LOG LogAddEnd() = std::cout << __LINE__ << " " << "["<<__FUNCTION__<<"] "
#define LOG_NEW_LINE std::cout << std::endl
}
static int LastErrorNo()
{
#if WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
#if WIN32
static std::string LastErrorString()
{
LPSTR pszError = NULL;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US), (LPSTR)&pszError, 0, NULL);
std::string&& szErrorString = std::string(pszError);
LocalFree(pszError);
return szErrorString;
}
#else
static std::string LastErrorString()
{
return std::string(strerror(LastErrorNo()));
}
#endif
#define LOG_NET_ERR_INFO LOG << "net_errno:" << LastErrorNo() << " msg:" << LastErrorString()
namespace NetUtils {
void SleepSomeSeconds(int seconds)
{
#ifdef WIN32
Sleep(seconds * 1000);
#else
sleep(seconds);
#endif // WIN32
}
// 在mac上没有效果哎,win32下有效
std::string GetLocalIPAddress()
{
char ip[128] = { 0 };
addrinfo hints;
addrinfo *answer = nullptr,*curr = nullptr;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 */
hints.ai_protocol = 0; /* Any protocol */
hints.ai_socktype = SOCK_STREAM;
// mac上第二个参数传nullptr,报错。
int ret = getaddrinfo("", "80", &hints, &answer);
if (ret == 0)
{
for (curr = answer; curr != NULL; curr = curr->ai_next)
{
if (curr->ai_family == AF_INET)
{
sockaddr_in *addr = reinterpret_cast<sockaddr_in *>(curr->ai_addr);
inet_ntop(curr->ai_family, &addr->sin_addr, ip, sizeof(ip));
if (strcmp(ip, "127.0.0.1") == 0)
{
continue;
}
}
else if (curr->ai_family == AF_INET6)
{
sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6 *>(curr->ai_addr);
inet_ntop(curr->ai_family, &addr->sin6_addr, ip, sizeof(ip));
if (strcmp(ip, "::1") == 0)
{
continue;
}
}
else
{
LOG << "check it";
continue;
}
break;
}
}
freeaddrinfo(answer);
return ip;
}
std::string GetLocalIP(int socket_id)
{
sockaddr_storage local_addr;
socklen_t len = sizeof(local_addr);
if (getsockname(socket_id, (sockaddr*)&local_addr, &len) != 0)
{
LOG_NET_ERR_INFO;
return "";
}
void* ip_ptr = nullptr;
if (local_addr.ss_family == AF_INET)
{
ip_ptr = &((sockaddr_in *)&local_addr)->sin_addr;
}
else if (local_addr.ss_family == AF_INET6)
{
ip_ptr = &((sockaddr_in6 *)&local_addr)->sin6_addr;
}
else
{
return "";
}
char ip_str[128] = { 0 };
auto* ptr = inet_ntop(local_addr.ss_family, ip_ptr, ip_str, sizeof(ip_str));
if (ptr) {
return ptr;
}
else
{
LOG_NET_ERR_INFO;
return "";
}
}
int GetLocalPort(int socket_id)
{
sockaddr_storage local_addr;
socklen_t len;
len = sizeof(local_addr);
if (getsockname(socket_id, (sockaddr*)&local_addr, &len) != 0)
{
LOG_NET_ERR_INFO;
return -1;
}
if (local_addr.ss_family == AF_INET)
{
sockaddr_in *addr4 = (sockaddr_in *)&local_addr;
return ntohs(addr4->sin_port);
}
else if (local_addr.ss_family == AF_INET6)
{
sockaddr_in6 *addr6 = (sockaddr_in6 *)&local_addr;
return ntohs(addr6->sin6_port);
}
else
{
return -1;
}
}
std::string GetPeerIP(int socket_id)
{
sockaddr_storage local_addr;
socklen_t len = sizeof(local_addr);
if (getpeername(socket_id, (sockaddr*)&local_addr, &len) != 0)
{
LOG << LastErrorNo() << LastErrorString();
return "error: getsockname error";
}
void* ip_ptr = nullptr;
if (local_addr.ss_family == AF_INET)
{
ip_ptr = &((sockaddr_in *)&local_addr)->sin_addr;
}
else if (local_addr.ss_family == AF_INET6)
{
ip_ptr = &((sockaddr_in6 *)&local_addr)->sin6_addr;
}
else
{
return "";
}
char ip_str[128] = { 0 };
auto* ptr = inet_ntop(local_addr.ss_family, ip_ptr, ip_str, sizeof(ip_str));
if (ptr) {
return ptr;
}
else
{
LOG_NET_ERR_INFO;
return "";
}
}
int GetPeerPort(int socket_id)
{
sockaddr_storage local_addr;
socklen_t len;
len = sizeof(local_addr);
if (getpeername(socket_id, (sockaddr*)&local_addr, &len) != 0)
{
LOG_NET_ERR_INFO;
return -1;
}
if (local_addr.ss_family == AF_INET)
{
sockaddr_in *addr4 = (sockaddr_in *)&local_addr;
return ntohs(addr4->sin_port);
}
else if (local_addr.ss_family == AF_INET6)
{
sockaddr_in6 *addr6 = (sockaddr_in6 *)&local_addr;
return ntohs(addr6->sin6_port);
}
else
{
return -1;
}
}
static void CloseSocket(int socket_id)
{
if (socket_id != -1)
{
#if WIN32
closesocket(socket_id);
#else
close(socket_id);
#endif
}
}
static void SetKeepAlive(int socket_id, int idle_time, int interval_time)
{
#if _WIN32
struct StTcpKeepalive
{
uint32_t onoff;
uint32_t keepalivetime;
uint32_t keepaliveinterval;
};
StTcpKeepalive options;
options.onoff = 1;
options.keepalivetime = idle_time * 1000;
options.keepaliveinterval = interval_time * 1000;
DWORD cbBytesReturned;
WSAIoctl(socket_id, SIO_KEEPALIVE_VALS, &options, sizeof(options), NULL, 0, &cbBytesReturned, NULL, NULL);
#else
int keepAlive = 1; // 开启keepalive属性. 缺省值: 0(关闭)
int keepIdle = idle_time; // 如果在idle秒内没有任何数据交互,则进行探测. 缺省值:7200(s)
int keepInterval = interval_time; // 探测时发探测包的时间间隔为interval秒. 缺省值:75(s)
int keepCount = 2; // 探测重试的次数. 全部超时则认定连接失效..缺省值:9(次)
setsockopt(socket_id, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepAlive, sizeof(keepAlive));
#ifdef __linux__
setsockopt(socket_id, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle));
#endif
setsockopt(socket_id, IPPROTO_TCP, TCP_KEEPINTVL, (void*)&keepInterval, sizeof(keepInterval));
setsockopt(socket_id, IPPROTO_TCP, TCP_KEEPCNT, (void*)&keepCount, sizeof(keepCount));
#endif
}
bool SetNoBlock(int fd)
{
#ifdef WIN32
unsigned long flag = 1;
if (ioctlsocket(fd, FIONBIO, (unsigned long *)&flag) < 0)
{
LOG << "ioctlsocket set fail";
return false;
}
return true;
#else
int flags;
if ((flags = fcntl(fd, F_GETFL)) == -1)
{
LOG << "fcntl get fail";
return false;
}
flags |= O_NONBLOCK; //设置非阻塞标志位
if (fcntl(fd, F_SETFL, flags) == -1)
{
LOG << "fcntl set fail";
return false;
}
return true;
#endif
}
bool IsAlive(int socket_id) {
int type = 0;
socklen_t typesize = sizeof(type);
int iCode = getsockopt(socket_id, SOL_SOCKET, SO_ERROR, (char*)&type, &typesize);
return (iCode == 0);
}
// @params sock_type
// TCP : SOCK_STREAM
// UDP : SOCK_DGRAM
int Connect(const std::string hostname_or_ip, uint16_t port, int sock_type)
{
addrinfo *answer, hint, *curr;
int ret;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;// 也可以用AF_INET或AF_INET6指定ipv4或ipv6
hint.ai_socktype = sock_type;
if ((ret = getaddrinfo(hostname_or_ip.c_str(), std::to_string(port).c_str(), &hint, &answer)) != 0) {
LOG << "getaddrinfo fail errno:" << LastErrorNo() << " errstr:" << LastErrorString()
<< " extra_info:" << gai_strerror(ret);
return -1;
}
sockaddr_in sockaddr_ipv4;
sockaddr_in6 sockaddr_ipv6;
bool bValid = false;
bool bIpv6Flag = false;
for (curr = answer; curr != NULL; curr = curr->ai_next)
{
switch (curr->ai_family)
{
case AF_INET:
{
auto* sockaddr_ipv4_ptr = reinterpret_cast<sockaddr_in *>(curr->ai_addr);
memset(&sockaddr_ipv4, 0, sizeof(sockaddr_ipv4));
sockaddr_ipv4.sin_family = curr->ai_family;
sockaddr_ipv4.sin_addr = sockaddr_ipv4_ptr->sin_addr;
sockaddr_ipv4.sin_port = htons(port);
bValid = true;
}
break;
case AF_INET6:
{
auto* sockaddr_ipv6_ptr = reinterpret_cast<sockaddr_in6 *>(curr->ai_addr);
memset(&sockaddr_ipv6, 0, sizeof(sockaddr_ipv6));
sockaddr_ipv6.sin6_family = curr->ai_family;
sockaddr_ipv6.sin6_addr = sockaddr_ipv6_ptr->sin6_addr;
sockaddr_ipv6.sin6_port = htons(port);
bValid = true;
bIpv6Flag = true;
}
break;
}
if (bValid)
{
break;
}
}
freeaddrinfo(answer);
if (!bValid)
{
LOG << "getaddrinfo does not get valid sock_addr";
return -1;
}
int addr_af = bIpv6Flag ? AF_INET6 : AF_INET;
sockaddr * addr_ptr = bIpv6Flag ? (sockaddr *)&sockaddr_ipv6 : (sockaddr *)&sockaddr_ipv4;
int addr_len = bIpv6Flag ? sizeof(sockaddr_ipv6) : sizeof(sockaddr_ipv4);
int socket_id = socket(addr_af, sock_type, 0);
if (socket_id < 0) {
LOG_NET_ERR_INFO;
return -1;
}
if (connect(socket_id, addr_ptr, addr_len) < 0) {
LOG_NET_ERR_INFO;
CloseSocket(socket_id);
return -1;
}
SetNoBlock(socket_id);
// TCP
if(sock_type == SOCK_STREAM)
{
const int on = 1;
setsockopt(socket_id, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(on));
}
#ifndef WIN32 // 信号会引起崩溃
{
const int set = 1;
setsockopt(socket_id, SOL_SOCKET, SO_NOSIGPIPE, (const void *)&set, sizeof(set));
}
#endif
return socket_id;
}
int Listen(uint16_t port, int sock_type, std::string _bindAddress = "")
{
const int on = 1;
int ret;
int socket_id = -1;
sockaddr_in sockaddr_ipv4;
memset(&sockaddr_ipv4, 0, sizeof(sockaddr_ipv4));
sockaddr_ipv4.sin_family = AF_INET;
sockaddr_ipv4.sin_addr.s_addr = INADDR_ANY;
sockaddr_ipv4.sin_port = htons(port);
// bind address
if (_bindAddress.length() > 0)
{
inet_pton(AF_INET, _bindAddress.c_str(), (void*)&sockaddr_ipv4.sin_addr);
}
socket_id = socket(AF_INET, sock_type, 0);
if (socket_id < 0)
{
LOG_NET_ERR_INFO;
return -1;
}
// 重复使用本地址与socket文件进行绑定
// 如果不设置系统,会保留此连接直到最后一引用才释放,进程结束后系统需要几分钟后才能重新进行绑定
setsockopt(socket_id, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
SetNoBlock(socket_id);
ret = bind(socket_id, (struct sockaddr*)&sockaddr_ipv4, sizeof(sockaddr_ipv4));
if (ret != 0)
{
LOG_NET_ERR_INFO;
CloseSocket(socket_id);
return -1;
}
listen(socket_id, 50);
return socket_id;
}
int Accept(int socket_id)
{
sockaddr_storage client;
socklen_t client_len = sizeof(client);
/* new client */
int fd = accept(socket_id, (struct sockaddr *)&client, &client_len);
if (fd)
{
SetNoBlock(fd);
}
return fd;
}
}
// 定义了个简单报文协议,开头两个字节的长度,| len(2) | data |
// 主要用于TCP
class CodeRingBuf {
public:
CodeRingBuf()
{
_head = 0;
_tail = 0;
}
int GetUsedBufLength()
{
return _tail - _head;
}
int GetFreeBufLength()
{
return BUF_REAL_LEN - GetUsedBufLength();
}
void Clear()
{
_head = _tail = 0;
}
// 输出缓存相关函数
bool CheckFreeBufEnough(int len)
{
return GetFreeBufLength() >= len;
}
inline void _PutInOneChar(uint8_t ch)
{
_buf[_tail&BUF_REAL_LEN] = ch;
++_tail;
}
void PutInOneCode(const char* buf, int len)
{
len += 2;// 加上两个长度字节
assert(GetFreeBufLength() >= len);
_PutInOneChar((len >> 8) & 0xff);
_PutInOneChar(len & 0xff);
len -= 2;
for (int i = 0; i < len; ++i)
{
_PutInOneChar(buf[i]);
}
}
int CopyInfo(char* out_buf, int len) {
int copy_len = GetUsedBufLength();
if (len < copy_len) copy_len = len;
for (int i = 0; i < copy_len; ++i)
{
out_buf[i] = _buf[(_head + i)&BUF_REAL_LEN];
}
return copy_len;
}
void Consume(int len)
{
assert(GetUsedBufLength() >= len);
_head += len;
}
void PutIn(const char* buf, int len)
{
assert(GetFreeBufLength() >= len);
for (int i = 0; i < len; ++i)
{
_PutInOneChar(buf[i]);
}
}
int GetOutOneCode(char* out_buf, int buf_len)
{
int used_buf = GetUsedBufLength();
if (used_buf < 2)
{
return -1;
}
int len = _buf[_head&BUF_REAL_LEN] << 8;
len |= _buf[(_head + 1)&BUF_REAL_LEN];
if (len < 2 || len > BUF_REAL_LEN)
{
LOG << "protocol error len=" << len;
Clear();
return -1;
}
if (GetUsedBufLength() < len)
{
return -1;
}
len -= 2;
if (buf_len < len) {
assert(!"this situation should not happen");
Clear();
return -1;
}
_head += 2;
for (int i = 0; i < len; ++i)
{
out_buf[i] = _buf[_head&BUF_REAL_LEN];
++_head;
}
return len;
}
private:
// 代码有优化
// buf长度一定要是2^n,有效长度是2^n-1.
// 如果总流量<2^32,_tail就是总流量
const static int BUF_LEN = 1 << 16;
const static int BUF_REAL_LEN = BUF_LEN - 1;
uint8_t _buf[BUF_LEN];
uint32_t _head;
uint32_t _tail;
};
class NetConnect {
public:
virtual ~NetConnect() {};
virtual int Connect(const std::string hostname_or_ip, uint16_t port) = 0;
virtual void SendOneCode(const char* msg, int len) = 0;
virtual int RecvOneCode(char* buf, int len) = 0;
// 测试用
virtual void SendMsg(const std::string msg)
{
SendOneCode(msg.c_str(), msg.length());
}
virtual std::string RecvMsg() {
char buf[1500] = {0};
// 一定要读到一组数据才结束
while (RecvOneCode(buf, sizeof(buf)) < 0);
return buf;
}
};
class TCPConnect :public NetConnect {
public:
TCPConnect() :_socket_id(-1), _is_breaked_by_server(false) {}
TCPConnect& operator=(int socket_id)
{
_socket_id = socket_id;
_is_breaked_by_server = false;
return *this;
}
void LogInfo(std::string head)
{
LOG << head
<< " sock = " << NetUtils::GetLocalIP(_socket_id)
<< ":" << NetUtils::GetLocalPort(_socket_id)
<< " peer = " << NetUtils::GetPeerIP(_socket_id)
<< ":" << NetUtils::GetPeerPort(_socket_id);
}
int GetSocketId()
{
return _socket_id;
}
int Connect(const std::string hostname_or_ip, uint16_t port)
{
_send_buf.Clear();
_recv_buf.Clear();
_socket_id = NetUtils::Connect(hostname_or_ip, port, SOCK_STREAM);
return _socket_id;
}
void SendOneCode(const char* msg, int len)
{
if (_send_buf.CheckFreeBufEnough(len + 2))
{
_send_buf.PutInOneCode(msg, len);
}
else
{
LOG << "buf overflow";
return;
}
SendBuf();
}
void SendBuf()
{
if (_send_buf.GetUsedBufLength() > 0)
{
char buf[1024];
int send_len,success_len;
while ((send_len = _send_buf.CopyInfo(buf, sizeof(buf))) > 0)
{
success_len = send(_socket_id, buf, send_len, 0);
if (success_len < 0)
{
// todo(check errno)
break;
}
_send_buf.Consume(success_len);
}
}
}
int RecvOneCode(char* buf, int len)
{
// first read buf
{
int code_len = _recv_buf.GetOutOneCode(buf, len);
if (code_len >= 0) {
return code_len;
}
}
for (;;)
{
char buf[1024];
int recv_len;
recv_len = recv(_socket_id, buf, len, 0);
if (recv_len > 0)
{
if (_recv_buf.CheckFreeBufEnough(recv_len))
{
_recv_buf.PutIn(buf, recv_len);
}
else
{
LOG << "buf overflow";
// todo(reset connect)
break;
}
}
else if (recv_len == 0)
{
// TCP recv()==0, connect is breaked
break;
}
else if (recv_len < 0)
{
// todo(check errno)
break;
}
}
// last read buf
{
int code_len = _recv_buf.GetOutOneCode(buf, len);
if (code_len >= 0) {
return code_len;
}
}
// get one code fail
return -1;
}
private:
int _socket_id;
bool _is_breaked_by_server;
CodeRingBuf _send_buf;
CodeRingBuf _recv_buf;
};
class UDPConnect :public NetConnect {
public:
UDPConnect():_socket_id(-1) {}
UDPConnect& operator=(int socket_id)
{
_socket_id = socket_id;
return *this;
}
UDPConnect(int socket_id) : _socket_id(socket_id) {}
int GetSocketId()
{
return _socket_id;
}
void LogInfo(std::string head)
{
LOG << head
<< " sock = " << NetUtils::GetLocalIP(_socket_id)
<< ":" << NetUtils::GetLocalPort(_socket_id);
}
int Connect(const std::string hostname_or_ip, uint16_t port)
{
_socket_id = NetUtils::Connect(hostname_or_ip, port, SOCK_DGRAM);
return _socket_id;
}
void SendOneCode(const char* msg, int len)
{
// UDP不用分包
int success_len = send(_socket_id, msg, len, 0);
if (success_len < 0)
{
// todo(check errno)
}
}
int RecvOneCode(char* buf, int len)
{
int success_len = recv(_socket_id, buf, len, 0);
if (success_len < 0)
{
// todo(check errno)
return -1;
}
return success_len;
}
private:
int _socket_id;
};
class TCPListenConnect {
public:
TCPListenConnect():_socket_id(-1){}
void LogInfo()
{
LOG << "socket_id:" << _socket_id
<< " listen on " << NetUtils::GetLocalIP(_socket_id)
<< ":" << NetUtils::GetLocalPort(_socket_id);
}
int GetSocketId()
{
return _socket_id;
}
int Listen(uint16_t port, std::string bind_address = "")
{
_socket_id = NetUtils::Listen(port, SOCK_STREAM, bind_address);
return _socket_id;
}
int Accept()
{
return NetUtils::Accept(_socket_id);
}
private:
int _socket_id;
};
class UDPListenConnect {
public:
UDPListenConnect():_socket_id(-1){}
void LogInfo()
{
LOG << "socket_id:" << _socket_id
<< " listen on " << NetUtils::GetLocalIP(_socket_id)
<< ":" << NetUtils::GetLocalPort(_socket_id);
}
int GetSocketId()
{
return _socket_id;
}
int Listen(uint16_t port, std::string bind_address = "")
{
_socket_id = NetUtils::Listen(port, SOCK_DGRAM, bind_address);
return _socket_id;
}
// 测试函数,反射多少包才结束,
void ReflectALL(int num)
{
sockaddr_storage client;
socklen_t client_len = sizeof(client);
char buf[1024];
int recv_len;
for (;;)
{
recv_len = recvfrom(_socket_id, buf, sizeof(buf), 0, (sockaddr*)&client, &client_len);
if (recv_len >= 0)
{
sendto(_socket_id, buf, recv_len, 0, (sockaddr*)&client, client_len);
--num;
}
else
{
// todo(check errno)
if (num <= 0)
break;
}
}
}
private:
int _socket_id;
};
int main() {
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
LOG << LastErrorNo() << LastErrorString();
return 0;
};
#endif
std::string local_ip = "127.0.0.1";
#ifdef WIN32
LOG << "local ip = " << NetUtils::GetLocalIPAddress();
#endif
LOG_NEW_LINE;
LOG << "TCP no block test start";
{
TCPListenConnect listen_connect;
listen_connect.Listen(8080);
listen_connect.LogInfo();
TCPConnect client_connect;
client_connect.Connect(local_ip, 8080);
int id;
TCPConnect server_connect;
for (;;)
{
id = listen_connect.Accept();
if (id > 0)
{
server_connect = id;
break;
}
}
client_connect.LogInfo("client");
server_connect.LogInfo("server");
client_connect.SendMsg("hello");
LOG << "server recv: " << server_connect.RecvMsg();
server_connect.SendMsg("hi");
LOG << "client recv: " << client_connect.RecvMsg();
}
LOG_NEW_LINE;
LOG << "UDP no block test start";
{
UDPListenConnect listen_connect;
listen_connect.Listen(8080);
listen_connect.LogInfo();
UDPConnect client_connect;
client_connect.Connect(local_ip, 8080);
client_connect.LogInfo("client");
client_connect.SendMsg("hello");
listen_connect.ReflectALL(1);
LOG << "client reflect: " << client_connect.RecvMsg();
}
#ifdef WIN32
WSACleanup();
#endif // WIN32
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Lua
1
https://gitee.com/treert/lua_learn.git
git@gitee.com:treert/lua_learn.git
treert
lua_learn
lua_learn
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /