27 WORD sockVersion = MAKEWORD(2, 2);
29 if (WSAStartup(sockVersion, &wsaData) != 0) {
31 throw std::runtime_error(
"Winsock server Init failed");
33 addr_len =
sizeof(SOCKADDR);
35 tcpClient = socket(AF_INET, SOCK_STREAM, 0);
37 throw std::runtime_error(
"socket client error");
39 addrCli.sin_family = AF_INET;
40 addrCli.sin_port = htons(port);
41 addrCli.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
46 tcpServer = socket(AF_INET, SOCK_STREAM, 0);
48 throw "socket server error";
51 addrSer.sin_family = AF_INET;
52 addrSer.sin_port = htons(port);
53 addrSer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
55 if (bind(
tcpServer, (SOCKADDR *) &addrSer, addr_len) == SOCKET_ERROR) {
56 throw "socket bind error";
59 throw "socket listen error";
64 addr_len =
sizeof(
struct sockaddr_in);
67 tcpClient = socket(AF_INET, SOCK_STREAM, 0);
69 throw "socket client error";
71 addrCli.sin_family = AF_INET;
72 addrCli.sin_port = htons(port);
73 addrCli.sin_addr.s_addr = inet_addr(ip.c_str());
75 setsockopt(
tcpClient, SOL_SOCKET, SO_RCVTIMEO, &timeout,
sizeof(timeout));
78 tcpServer = socket(AF_INET, SOCK_STREAM, 0);
80 throw "socket server error";
83 addrSer.sin_family = AF_INET;
84 addrSer.sin_port = htons(port);
85 addrSer.sin_addr.s_addr = htonl(INADDR_ANY);
87 if (bind(
tcpServer, (
struct sockaddr*)&addrSer, addr_len) == -1) {
88 throw "socket bind error";
91 throw "socket listen error";
104 ioctlsocket(
tcpClient, FIONBIO, (
unsigned long *) &ul);
105 recv = connect(
tcpClient, (SOCKADDR *) &addrCli, addr_len);
107 ioctlsocket(
tcpClient, FIONBIO, (
unsigned long *) &ul);
110 fcntl(
tcpClient, F_SETFL, ul | O_NONBLOCK);
111 recv = connect(
tcpClient, (
struct sockaddr*)&addrCli, addr_len);
113 fcntl(
tcpClient, F_SETFL, ul & ~O_NONBLOCK);
118 timeval tv = {(int)connect_time, 0};
128 tv = {(int)connect_time, 0};
133 printf(
"select error\n");
136 printf(
"select time out\n");
139 printf(
"select time out\n");
171 int recv_count = recv(s, buf, len, 0);
172 if (recv_count > 0) {
182 int sent_count = send(s, buf, len, 0);
183 if (sent_count > 0) {
209 if (stopped && *stopped) {
216 }
else if (rxLen > 0) {
218 if (totalLen >= len) {
234 if (stopped && *stopped) {
242 }
else if (stLen > 0) {
244 if (totalLen >= len) {
void Init(bool update, unsigned short int port=0, std::string ip="")
int SendData(int s, char *buf, int len)
int ConnectServer(float connect_time=SELECT_TIMEOUT)
SocketGenerator(unsigned short int port=0, std::string ip="", bool mode=true)
int RecvData(int s, char *buf, int len)
int TcpRecvBytes(SocketGenerator *s, char *buf, size_t len, bool *stopped=nullptr)
int TcpSendBytes(SocketGenerator *s, char *buf, size_t len, bool *stopped=nullptr)