- Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathnetgame.cpp
More file actions
Latest commit
executable file
·126 lines (112 loc) · 2.5 KB
/
Copy pathnetgame.cpp
File metadata and controls
executable file
·126 lines (112 loc) · 2.5 KB
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
#defineFD_SETSIZE2
#include<winsock.h>
#include"netgame.h"
staticconst 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);
}
boolnetgameclient::init()
{
iSock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
// unsigned long nonblocking=1;
unsignedlong nonblocking=0;
#ifdef _WINDOWS
ioctlsocket(iSock,FIONBIO,&nonblocking);
#else
ioctl(iSock,FIONBIO,&nonblocking);
#endif
returntrue;
}
netgameclient::~netgameclient()
{
closesocket(iSock);
}
boolnetgameclient::send(conststructcommand *cmd)
{
structsockaddr_in saddr;
saddr.sin_addr.S_un.S_addr=iAddr;
saddr.sin_port=htons(iPort);
saddr.sin_family=AF_INET;
return (::sendto(iSock,(constchar *)cmd,sizeof(structcommand),0,(conststructsockaddr*)&saddr,sizeof(saddr)) == sizeof(structcommand));
}
netgameserver::netgameserver(int port)
{
iBufRead=0;
iPort=port;
// FD_ZERO(&iReadSet);
}
boolnetgameserver::init()
{
structsockaddr_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));
unsignedlong nonblocking=1;
#ifdef _WINDOWS
ioctlsocket(iSock,FIONBIO,&nonblocking);
#else
ioctl(iSock,FIONBIO,&nonblocking);
#endif
// FD_SET(iSock,&iReadSet);
returntrue;
}
netgameserver::~netgameserver()
{
closesocket(iSock);
}
boolnetgameserver::recv(structcommand &cmd)
{
structtimeval 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)
returnfalse;
#else
returnfalse;
#endif
}
else
{
iBufRead += retval;
if (iBufRead == sizeof(iCmd))
{
iBufRead=0;
cmd=iCmd;
returntrue;
}
else
returnfalse;
}
}
returnfalse;
}