Chat Example Server.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. // ----------------------------------------------------------------------
  11. // RakNet version 1.0
  12. // Filename ChatExample.cpp
  13. // Very basic chat engine example
  14. // ----------------------------------------------------------------------
  15. #include "MessageIdentifiers.h"
  16. #include "RakPeerInterface.h"
  17. #include "RakNetStatistics.h"
  18. #include "RakNetTypes.h"
  19. #include "BitStream.h"
  20. #include "RakSleep.h"
  21. #include "PacketLogger.h"
  22. #include <assert.h>
  23. #include <cstdio>
  24. #include <cstring>
  25. #include <stdlib.h>
  26. #include "Kbhit.h"
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include "Gets.h"
  30. #if LIBCAT_SECURITY==1
  31. #include "SecureHandshake.h" // Include header for secure handshake
  32. #endif
  33. #if defined(_CONSOLE_2)
  34. #include "Console2SampleIncludes.h"
  35. #endif
  36. // We copy this from Multiplayer.cpp to keep things all in one file for this example
  37. unsigned char GetPacketIdentifier(RakNet::Packet *p);
  38. #ifdef _CONSOLE_2
  39. _CONSOLE_2_SetSystemProcessParams
  40. #endif
  41. int main(void)
  42. {
  43. // Pointers to the interfaces of our server and client.
  44. // Note we can easily have both in the same program
  45. RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();
  46. RakNet::RakNetStatistics *rss;
  47. server->SetIncomingPassword("Rumpelstiltskin", (int)strlen("Rumpelstiltskin"));
  48. server->SetTimeoutTime(30000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
  49. // RakNet::PacketLogger packetLogger;
  50. // server->AttachPlugin(&packetLogger);
  51. #if LIBCAT_SECURITY==1
  52. cat::EasyHandshake handshake;
  53. char public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES];
  54. char private_key[cat::EasyHandshake::PRIVATE_KEY_BYTES];
  55. handshake.GenerateServerKey(public_key, private_key);
  56. server->InitializeSecurity(public_key, private_key, false);
  57. FILE *fp = fopen("publicKey.dat","wb");
  58. fwrite(public_key,sizeof(public_key),1,fp);
  59. fclose(fp);
  60. #endif
  61. // Holds packets
  62. RakNet::Packet* p;
  63. // GetPacketIdentifier returns this
  64. unsigned char packetIdentifier;
  65. // Record the first client that connects to us so we can pass it to the ping function
  66. RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
  67. // Holds user data
  68. char portstring[30];
  69. printf("This is a sample implementation of a text based chat server.\n");
  70. printf("Connect to the project 'Chat Example Client'.\n");
  71. printf("Difficulty: Beginner\n\n");
  72. // A server
  73. puts("Enter the server port to listen on");
  74. Gets(portstring,sizeof(portstring));
  75. if (portstring[0]==0)
  76. strcpy(portstring, "1234");
  77. puts("Starting server.");
  78. // Starting the server is very simple. 2 players allowed.
  79. // 0 means we don't care about a connectionValidationInteger, and false
  80. // for low priority threads
  81. // I am creating two socketDesciptors, to create two sockets. One using IPV6 and the other IPV4
  82. RakNet::SocketDescriptor socketDescriptors[2];
  83. socketDescriptors[0].port=atoi(portstring);
  84. socketDescriptors[0].socketFamily=AF_INET; // Test out IPV4
  85. socketDescriptors[1].port=atoi(portstring);
  86. socketDescriptors[1].socketFamily=AF_INET6; // Test out IPV6
  87. bool b = server->Startup(4, socketDescriptors, 2 )==RakNet::RAKNET_STARTED;
  88. server->SetMaximumIncomingConnections(4);
  89. if (!b)
  90. {
  91. printf("Failed to start dual IPV4 and IPV6 ports. Trying IPV4 only.\n");
  92. // Try again, but leave out IPV6
  93. b = server->Startup(4, socketDescriptors, 1 )==RakNet::RAKNET_STARTED;
  94. if (!b)
  95. {
  96. puts("Server failed to start. Terminating.");
  97. exit(1);
  98. }
  99. }
  100. server->SetOccasionalPing(true);
  101. server->SetUnreliableTimeout(1000);
  102. DataStructures::List< RakNet::RakNetSocket2* > sockets;
  103. server->GetSockets(sockets);
  104. printf("Socket addresses used by RakNet:\n");
  105. for (unsigned int i=0; i < sockets.Size(); i++)
  106. {
  107. printf("%i. %s\n", i+1, sockets[i]->GetBoundAddress().ToString(true));
  108. }
  109. printf("\nMy IP addresses:\n");
  110. for (unsigned int i=0; i < server->GetNumberOfAddresses(); i++)
  111. {
  112. RakNet::SystemAddress sa = server->GetInternalID(RakNet::UNASSIGNED_SYSTEM_ADDRESS, i);
  113. printf("%i. %s (LAN=%i)\n", i+1, sa.ToString(false), sa.IsLANAddress());
  114. }
  115. printf("\nMy GUID is %s\n", server->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());
  116. puts("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'pingip' to ping an ip address\n'ban' to ban an IP from connecting.\n'kick to kick the first connected player.\nType to talk.");
  117. char message[2048];
  118. // Loop for input
  119. while (1)
  120. {
  121. // This sleep keeps RakNet responsive
  122. RakSleep(30);
  123. if (kbhit())
  124. {
  125. // Notice what is not here: something to keep our network running. It's
  126. // fine to block on gets or anything we want
  127. // Because the network engine was painstakingly written using threads.
  128. Gets(message,sizeof(message));
  129. if (strcmp(message, "quit")==0)
  130. {
  131. puts("Quitting.");
  132. break;
  133. }
  134. if (strcmp(message, "stat")==0)
  135. {
  136. rss=server->GetStatistics(server->GetSystemAddressFromIndex(0));
  137. StatisticsToString(rss, message, 2);
  138. printf("%s", message);
  139. printf("Ping %i\n", server->GetAveragePing(server->GetSystemAddressFromIndex(0)));
  140. continue;
  141. }
  142. if (strcmp(message, "ping")==0)
  143. {
  144. server->Ping(clientID);
  145. continue;
  146. }
  147. if (strcmp(message, "pingip")==0)
  148. {
  149. printf("Enter IP: ");
  150. Gets(message,sizeof(message));
  151. printf("Enter port: ");
  152. Gets(portstring,sizeof(portstring));
  153. if (portstring[0]==0)
  154. strcpy(portstring, "1234");
  155. server->Ping(message, atoi(portstring), false);
  156. continue;
  157. }
  158. if (strcmp(message, "kick")==0)
  159. {
  160. server->CloseConnection(clientID, true, 0);
  161. continue;
  162. }
  163. if (strcmp(message, "getconnectionlist")==0)
  164. {
  165. RakNet::SystemAddress systems[10];
  166. unsigned short numConnections=10;
  167. server->GetConnectionList((RakNet::SystemAddress*) &systems, &numConnections);
  168. for (int i=0; i < numConnections; i++)
  169. {
  170. printf("%i. %s\n", i+1, systems[i].ToString(true));
  171. }
  172. continue;
  173. }
  174. if (strcmp(message, "ban")==0)
  175. {
  176. printf("Enter IP to ban. You can use * as a wildcard\n");
  177. Gets(message,sizeof(message));
  178. server->AddToBanList(message);
  179. printf("IP %s added to ban list.\n", message);
  180. continue;
  181. }
  182. // Message now holds what we want to broadcast
  183. char message2[2048];
  184. // Append Server: to the message so clients know that it ORIGINATED from the server
  185. // All messages to all clients come from the server either directly or by being
  186. // relayed from other clients
  187. message2[0]=0;
  188. const static char prefix[] = "Server: ";
  189. strncpy(message2, prefix, sizeof(message2));
  190. strncat(message2, message, sizeof(message2) - strlen(prefix) - 1);
  191. // message2 is the data to send
  192. // strlen(message2)+1 is to send the null terminator
  193. // HIGH_PRIORITY doesn't actually matter here because we don't use any other priority
  194. // RELIABLE_ORDERED means make sure the message arrives in the right order
  195. // We arbitrarily pick 0 for the ordering stream
  196. // RakNet::UNASSIGNED_SYSTEM_ADDRESS means don't exclude anyone from the broadcast
  197. // true means broadcast the message to everyone connected
  198. server->Send(message2, (const int) strlen(message2)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
  199. }
  200. // Get a packet from either the server or the client
  201. for (p=server->Receive(); p; server->DeallocatePacket(p), p=server->Receive())
  202. {
  203. // We got a packet, get the identifier with our handy function
  204. packetIdentifier = GetPacketIdentifier(p);
  205. // Check if this is a network message packet
  206. switch (packetIdentifier)
  207. {
  208. case ID_DISCONNECTION_NOTIFICATION:
  209. // Connection lost normally
  210. printf("ID_DISCONNECTION_NOTIFICATION from %s\n", p->systemAddress.ToString(true));;
  211. break;
  212. case ID_NEW_INCOMING_CONNECTION:
  213. // Somebody connected. We have their IP now
  214. printf("ID_NEW_INCOMING_CONNECTION from %s with GUID %s\n", p->systemAddress.ToString(true), p->guid.ToString());
  215. clientID=p->systemAddress; // Record the player ID of the client
  216. printf("Remote internal IDs:\n");
  217. for (int index=0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++)
  218. {
  219. RakNet::SystemAddress internalId = server->GetInternalID(p->systemAddress, index);
  220. if (internalId!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
  221. {
  222. printf("%i. %s\n", index+1, internalId.ToString(true));
  223. }
  224. }
  225. break;
  226. case ID_INCOMPATIBLE_PROTOCOL_VERSION:
  227. printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
  228. break;
  229. case ID_CONNECTED_PING:
  230. case ID_UNCONNECTED_PING:
  231. printf("Ping from %s\n", p->systemAddress.ToString(true));
  232. break;
  233. case ID_CONNECTION_LOST:
  234. // Couldn't deliver a reliable packet - i.e. the other system was abnormally
  235. // terminated
  236. printf("ID_CONNECTION_LOST from %s\n", p->systemAddress.ToString(true));;
  237. break;
  238. default:
  239. // The server knows the static data of all clients, so we can prefix the message
  240. // With the name data
  241. printf("%s\n", p->data);
  242. // Relay the message. We prefix the name for other clients. This demonstrates
  243. // That messages can be changed on the server before being broadcast
  244. // Sending is the same as before
  245. sprintf(message, "%s", p->data);
  246. server->Send(message, (const int) strlen(message)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->systemAddress, true);
  247. break;
  248. }
  249. }
  250. }
  251. server->Shutdown(300);
  252. // We're done with the network
  253. RakNet::RakPeerInterface::DestroyInstance(server);
  254. return 0;
  255. }
  256. // Copied from Multiplayer.cpp
  257. // If the first byte is ID_TIMESTAMP, then we want the 5th byte
  258. // Otherwise we want the 1st byte
  259. unsigned char GetPacketIdentifier(RakNet::Packet *p)
  260. {
  261. if (p==0)
  262. return 255;
  263. if ((unsigned char)p->data[0] == ID_TIMESTAMP)
  264. {
  265. RakAssert(p->length > sizeof(RakNet::MessageID) + sizeof(RakNet::Time));
  266. return (unsigned char) p->data[sizeof(RakNet::MessageID) + sizeof(RakNet::Time)];
  267. }
  268. else
  269. return (unsigned char) p->data[0];
  270. }
粤ICP备19079148号