-
Notifications
You must be signed in to change notification settings - Fork 8
/
netgame.cpp
executable file
·126 lines (112 loc) · 2.5 KB
/
netgame.cpp
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
// I do not need more than 2 sockets open
#define FD_SETSIZE 2
#include <winsock.h>
#include "netgame.h"
static const netinit NetInit;
netinit::netinit()
{
#if defined(_WINDOWS)
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
WSAStartup( wVersionRequested, &wsaData );
#endif
}
netinit::~netinit()
{
#if defined (_WINDOWS)
WSACleanup();
#endif
}
netgameclient::netgameclient(int port,char *hostname)
{
iPort=port;
hostent* hostInfo=gethostbyname(hostname);
if (hostInfo)
iAddr=*(long*)hostInfo->h_addr_list[0];
else
iAddr=htonl(INADDR_NONE);
}
bool netgameclient::init()
{
iSock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
// unsigned long nonblocking=1;
unsigned long nonblocking=0;
#ifdef _WINDOWS
ioctlsocket(iSock,FIONBIO,&nonblocking);
#else
ioctl(iSock,FIONBIO,&nonblocking);
#endif
return true;
}
netgameclient::~netgameclient()
{
closesocket(iSock);
}
bool netgameclient::send(const struct command *cmd)
{
struct sockaddr_in saddr;
saddr.sin_addr.S_un.S_addr=iAddr;
saddr.sin_port=htons(iPort);
saddr.sin_family=AF_INET;
return (::sendto(iSock,(const char *)cmd,sizeof(struct command),0,(const struct sockaddr*)&saddr,sizeof(saddr)) == sizeof(struct command));
}
netgameserver::netgameserver(int port)
{
iBufRead=0;
iPort=port;
// FD_ZERO(&iReadSet);
}
bool netgameserver::init()
{
struct sockaddr_in saddr;
saddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
saddr.sin_port=htons(iPort);
saddr.sin_family=AF_INET;
iSock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
bind(iSock,(const sockaddr*) &saddr,sizeof(saddr));
unsigned long nonblocking=1;
#ifdef _WINDOWS
ioctlsocket(iSock,FIONBIO,&nonblocking);
#else
ioctl(iSock,FIONBIO,&nonblocking);
#endif
// FD_SET(iSock,&iReadSet);
return true;
}
netgameserver::~netgameserver()
{
closesocket(iSock);
}
bool netgameserver::recv(struct command &cmd)
{
struct timeval tval={0,0};
// int selret=::select((int)iSock,&iReadSet,NULL,NULL,&tval);
// if (selret>0)
{
char *bufaddr=(char*)(&iCmd)+iBufRead;
int retval=::recv(iSock,bufaddr,sizeof(iCmd)-iBufRead,0);
if (retval == SOCKET_ERROR)
{
#ifdef _WINDOWS
if (WSAGetLastError() == WSAEWOULDBLOCK)
return false;
#else
return false;
#endif
}
else
{
iBufRead += retval;
if (iBufRead == sizeof(iCmd))
{
iBufRead=0;
cmd=iCmd;
return true;
}
else
return false;
}
}
return false;
}