Пример #1
0
/* main */
int main(int argc, const char *argv[])
{
	char str[SIZE_MAX];

	printf("Please input str:");
	Gets(str, sizeof(str));
	while (strlen(str) > 0) {
		find_number(str);
		printf("\nPlease input str:");
		Gets(str, sizeof(str));
	}

	return 0;
}
Пример #2
0
char           *
inputline()
{
	/* and removes comment, newline, beginning and trailing blanks */
	/* used to get the TITLE line */
#if __TURBOC__ || SYSV || VMS
#define index strchr
#endif
	char            *cp;
	int             i;

	buf[0] = '\0';
	cp = Gets(buf);
	i = strlen(buf);
	if (i)
		buf[i - 1] = '\0';
	if ((cp = index(buf, '!')) != (char *) 0) {
		*cp-- = '\0';
	}
	while (cp >= buf && isspace(*cp)) {
		*cp-- = '\0';
	}
	/*EMPTY*/
	for (cp = buf; *cp != '\0' && isspace(*cp); cp++){
		;
	}
	return stralloc(cp, (char *) 0);
}
Пример #3
0
void CMsnDSClient::OnOpen()
{
	Debug(true);

	acl::string msg("VER ");
	msg << client_->Sid();
#if defined(MSN_PROTOCOL15)
	msg << " MSNP15 CVR0\r\n";
#elif defined(MSN_PROTOCOL21)
	msg << " MSNP21 CVR0\r\n";
#else
#error "unknow MSNP"
#endif
	Send(msg.c_str(), msg.length());

	msg = "CVR ";
	msg << client_->Sid() << " 0x0804 winnt 6.1.1 i386 MSNMSGR 15.4.3508.1109 MSNMSGR ";
	msg << account_.c_str();
#if defined(MSN_PROTOCOL15)
	msg << "\r\n";
#elif defined(MSN_PROTOCOL21)
	msg << " 0\r\n";
#else
#error "unknown MSNP"
#endif

	Send(msg.c_str(), msg.length());

	msg = "USR ";
	msg << client_->Sid() << " SSO I ";
	msg << account_.c_str() << "\r\n";
	Send(msg.c_str(), msg.length());
	Gets(true);
}
Пример #4
0
void main()
{
   char ch, file_name[25];
   //FILE *fp;
   int fd;
   int num_read;
 
   printf("Enter the name of file you wish to see\n");
   Gets(file_name);

   fd = open(file_name, O_RDONLY);
   if (fd < 0)
     {
       pError("Error while opening the file.\n");
       exit(EXIT_FAILURE);
     }
   printf("The contents of %s file are :\n", file_name);

   for (;;)
     {
       num_read = read(fd, &ch, sizeof(ch));
       if (num_read < '0')
	 {
	   perror("Error while reading the file.\n");
	   exit(EXIT_FAILURE);
	 }
       if (num_read == 0)
	 {
	   break;
	 }
       write(STDOUT_FILENO, ch, sizeof(ch));
     }
   return ch;
}
Пример #5
0
int main(void)
{
	char str[LEN];

	printf("Please input a string:");
	Gets(str, sizeof(str));
	puts(str);

	return 0;
}
Пример #6
0
/* insert */
static void insert(sqlite3 * db)
{
	char *sql = NULL, *err = NULL, name[NAME_LEN], gender[GENDER_LEN];
	int id, age, ret;

	printf("input id:");
	while (0 == scanf("%d", &id) || 0 == is_id(id)) {
		empty_cache();
		system("clear");
		printf("\ninput id:");
	}
	printf("input name:");
	empty_cache();
	Gets(name, sizeof(name));
	while (0 == is_name(name)) {
		system("clear");
		printf("input name:");
		Gets(name, sizeof(name));
	}
	printf("input gender:");
	Gets(gender, sizeof(gender));
	while (0 == is_gender(gender)) {
		system("clear");
		printf("input gender:");
		Gets(gender, sizeof(gender));
	}
	printf("input age:");
	while (0 == scanf("%d", &age) || 0 == is_age(age)) {
		empty_cache();
		system("clear");
		printf("\ninput age:");
	}
	sql =
	    sqlite3_mprintf("insert into employee values(%d,%Q,%Q,%d);",
			    id, name, gender, age);
	ret = sqlite3_exec(db, sql, NULL, NULL, &err);
	if (ret != SQLITE_OK) {
		fputs(err, stderr);
		fputs("\n", stderr);
	}
	sqlite3_free(sql);

}
Пример #7
0
EXPORT void g_prompt_for_maximum_number_of_components(void)
{
	char		s[Gets_BUF_SIZE];
 
	screen("Enter an upper bound for the "
	       "number of components (default = %d): ",max_n_comps);
	(void) Gets(s);
	if (s[0] != '\0')
	    (void) sscanf(s,"%d",&max_n_comps);
	max_n_comps += FIRST_DYNAMIC_COMPONENT;
	check_int_input("for the number of components",max_n_comps,1,1,GE_);
}		/*end g_prompt_for_maximum_number_of_components*/
Пример #8
0
inline void solve(void) {
    fread(buf, 1, 1000000000, stdin);
    Gets(ch);
    n = strlen(ch);
    root = L + (++pid), last = root;
    root->num = pid;
    for (register int i = 0; i < n; i++) Add(ch[i] - 'a');
    for (register int i = 1; i <= pid; i++) min_match[i] = L[i].val, ws[L[i].val]++;
    for (register int i = 1; i <= n; i++) ws[i] += ws[i - 1];
    for (register int i = 1; i <= pid; i++) d[ws[L[i].val]--] = i;
    m = 1;
    while (Gets(ch)) {
        ++m;
        Node *p = root;
        int l = strlen(ch), len = 0;
        for (register int i = 0; i < l; i++) {
            register int x = ch[i] - 'a';
            while (p && p->next[x] == 0) p = p->par;
            if (!p) p = root, len = 0;
            else {
                len = Min(len, p->val), p = p->next[x];
                match[p->num] = max(match[p->num], ++len);
            }
        }
        for (register int _ = pid; _ >= 2; _--) {
            register int i = d[_], f = L[i].par->num;
            min_match[i] = Min(min_match[i], match[i]);
            match[f] = Max(Min(match[f], L[f].val), match[i]);
        }
        memset(match, 0, sizeof(match[0]) * (pid + 1));
    }
    int Ans = 0;
    for (register int i = 1; i <= pid; i++) Ans = Max(Ans, min_match[i]);
    if (m == 1) puts("1");
    else printf("%d\n", Ans);
}
Пример #9
0
/*
 *	Application main entry
 */
EXPORT	void	appl_main( void )
{
	B	buf[256];
	INT	fin, n;

	/* initialize calendar date */
	init_calendar_date();

	/* command processing */
	for (fin = 0; fin == 0; ) {
		P("T2EX >> ");
		Gets(buf, sizeof(buf));
		for (n = strlen(buf); --n >= 0 && buf[n] <= ' '; ) 
			buf[n] = '\0';
		P("%s\n", buf);
		if (strncmp(buf, "quit", 1) == 0) {
			fin = 1;

		/* t-monitor */
#if 0
		} else if (strncmp(buf, "#", 1) == 0) {
			tm_command(&buf[1]);

		/* misc. command */
#endif
		} else {
			if (exec_cmd(buf) == 0) {
				P("q[uit]      quit\n");
				//P("# [cmd]     exec t-monitor command\n");
				P("?           command help\n");
				P("<command>   misc. command\n");
			}
		}
	}
	
	vd_printf("fin\n");
}
Пример #10
0
EXPORT	STRATIFICATION_TYPE prompt_for_stratification(
	const char *name)
{
	char s[Gets_BUF_SIZE];
	if (is_gravity() == YES)
	{
	    screen("\nInput the gravity stratified property %s\n",name);
	    screen("\tConstant state (CO) \n");
	    screen("\tConstant density (CD) \n");
	    screen("\tAdiabatic (AD) \n");
	    screen("\tIsothermal (IS, default) \n");
	    screen("Enter choice: ");
	    (void) Gets(s);
	    if ((strncmp(s,"CO",2) == 0) || (strncmp(s,"co",2) == 0))
	    {
	    	set_stratified_state(NULL);
	    	return CONSTANT;
	    }
	    else if ((strncmp(s,"CD",2) == 0) || (strncmp(s,"cd",2) == 0))
	    {
	       set_stratified_state(constant_density_stratified_state);
	       return CONSTANT_DENSITY;
	    }
	    else if ((strncmp(s,"AD",2) == 0) || (strncmp(s,"ad",2) == 0))
	    {
	    	set_stratified_state(isentropic_stratified_state);
	    	return ADIABATIC;
	    }
	    else
	    {
	    	set_stratified_state(isothermal_stratified_state);
	    	return ISOTHERMAL;
	    }
	}
	else
	    return CONSTANT;
}		/*end prompt_for_stratification*/
Пример #11
0
int main(void)
{
	char str[512];
	
	RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
	bool isServer;
	RakNet::Packet *packet;


	printf("(C) or (S)erver?\n");

	Gets(str, sizeof(str));
	if ((str[0]=='c')||(str[0]=='C'))
	{
		RakNet::SocketDescriptor sd;
		peer->Startup(1,&sd, 1);
		isServer = false;
	} else {
		RakNet::SocketDescriptor sd(SERVER_PORT,0);
		peer->Startup(MAX_CLIENTS, &sd, 1);
		isServer = true;
	}


	if (isServer)
	{
		printf("Starting the server.\n");
		// We need to let the server accept incoming connections from the clients
		peer->SetMaximumIncomingConnections(MAX_CLIENTS);
	} else {
		printf("Enter server IP or hit enter for 127.0.0.1\n");
		Gets(str, sizeof(str));
		if (str[0]==0){
			strcpy(str, "127.0.0.1");
		}
		printf("Starting the client.\n");
		peer->Connect(str, SERVER_PORT, 0,0);

	}

	while (1)
	{
		for (packet=peer->Receive(); packet; peer->DeallocatePacket(packet), packet=peer->Receive())
		{
			switch (packet->data[0])
			{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					printf("Another client has disconnected.\n");
					break;
				case ID_REMOTE_CONNECTION_LOST:
					printf("Another client has lost the connection.\n");
					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					printf("Our connection request has been accepted.\n");
					break;					
				case ID_NEW_INCOMING_CONNECTION:
					printf("A connection is incoming.\n");
					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					printf("The server is full.\n");
					break;
				case ID_DISCONNECTION_NOTIFICATION:
					if (isServer){
						printf("A client has disconnected.\n");
					} else {
						printf("We have been disconnected.\n");
					}
					break;
				case ID_CONNECTION_LOST:
					if (isServer){
						printf("A client lost the connection.\n");
					} else {
						printf("Connection lost.\n");
					}
					break;
				default:
					printf("Message with identifier %i has arrived.\n", packet->data[0]);
					break;
			}
		}
	}


	RakNet::RakPeerInterface::DestroyInstance(peer);

	return 0;
}
Пример #12
0
int main(void)
{
	RakNet::RakNetStatistics *rss;
	// Pointers to the interfaces of our server and client.
	// Note we can easily have both in the same program
	RakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();
//	client->InitializeSecurity(0,0,0,0);
	//RakNet::PacketLogger packetLogger;
	//client->AttachPlugin(&packetLogger);

	
	// Holds packets
	RakNet::Packet* p;

	// GetPacketIdentifier returns this
	unsigned char packetIdentifier;

	// Just so we can remember where the packet came from
	bool isServer;

	// Record the first client that connects to us so we can pass it to the ping function
	RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;

	// Crude interface

	// Holds user data
	char ip[64], serverPort[30];

	// A client
	isServer=false;

	printf("This is a sample implementation of a text based chat client.\n");
	printf("Connect to the project 'Chat Example Server'.\n");
	printf("Difficulty: Beginner\n\n");

	// Get our input
//#if 0
	char clientPort[30];
	puts("Enter the client port to listen on");
	Gets(clientPort,sizeof(clientPort));
	if (clientPort[0]==0)
		strcpy(clientPort, "0");
//#endif
	puts("Enter IP to connect to");
	Gets(ip, sizeof(ip));
	client->AllowConnectionResponseIPMigration(false);
	if (ip[0]==0)
		strcpy(ip, "127.0.0.1");
	// strcpy(ip, "natpunch.jenkinssoftware.com");
	
		
	puts("Enter the port to connect to");
	Gets(serverPort,sizeof(serverPort));
	if (serverPort[0]==0)
		strcpy(serverPort, "1234");

//#if 0	
	// Connecting the client is very simple.  0 means we don't care about
	// a connectionValidationInteger, and false for low priority threads
	RakNet::SocketDescriptor socketDescriptor(atoi(clientPort),0);
	socketDescriptor.socketFamily=AF_INET;
	client->Startup(8,&socketDescriptor, 1);
	client->SetOccasionalPing(true);
//#endif


#if LIBCAT_SECURITY==1
	char public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES];
	FILE *fp = fopen("publicKey.dat","rb");
	fread(public_key,sizeof(public_key),1,fp);
	fclose(fp);
#endif

#if LIBCAT_SECURITY==1
	RakNet::PublicKey pk;
	pk.remoteServerPublicKey=public_key;
	pk.publicKeyMode=RakNet::PKM_USE_KNOWN_PUBLIC_KEY;
	bool b = client->Connect(ip, atoi(serverPort), "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"), &pk)==RakNet::CONNECTION_ATTEMPT_STARTED;	
#else
	RakNet::ConnectionAttemptResult car = client->Connect(ip, atoi(serverPort), "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"), 0, 0, 20, 2000);
	RakAssert(car==RakNet::CONNECTION_ATTEMPT_STARTED);
#endif

	printf("\nMy IP addresses:\n");
	unsigned int i;
	for (i=0; i < client->GetNumberOfAddresses(); i++)
	{
		printf("%i. %s\n", i+1, client->GetLocalIP(i));
	}

	printf("My GUID is %s\n", client->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());
	puts("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'disconnect' to disconnect. 'connect' to reconnnect. Type to talk.");
	
	char message[2048];

	// Loop for input
	while (1)
	{
		// This sleep keeps RakNet responsive
#ifdef _WIN32
		Sleep(30);
#else
		usleep(30 * 1000);
#endif


		if (kbhit())
		{
			// Notice what is not here: something to keep our network running.  It's
			// fine to block on Gets or anything we want
			// Because the network engine was painstakingly written using threads.
			Gets(message,sizeof(message));

			if (strcmp(message, "quit")==0)
			{
				puts("Quitting.");
				break;
			}

			if (strcmp(message, "stat")==0)
			{
				
				rss=client->GetStatistics(client->GetSystemAddressFromIndex(0));
				StatisticsToString(rss, message, 2);
				printf("%s", message);
				printf("Ping=%i\n", client->GetAveragePing(client->GetSystemAddressFromIndex(0)));
			
				continue;
			}

			if (strcmp(message, "disconnect")==0)
			{
				printf("Enter index to disconnect: ");
				char str[32];
				Gets(str, sizeof(str));
				if (str[0]==0)
					strcpy(str,"0");
				int index = atoi(str);
				client->CloseConnection(client->GetSystemAddressFromIndex(index),false);
				printf("Disconnecting.\n");
				continue;
			}

			if (strcmp(message, "shutdown")==0)
			{
				client->Shutdown(100);
				printf("Shutdown.\n");
				continue;
			}


#if 0
			if (strcmp(message, "startup")==0)
			{
				bool b = client->Startup(8,&socketDescriptor, 1)==RakNet::RAKNET_STARTED;
				if (b)
					printf("Started.\n");
				else
					printf("Startup failed.\n");
				continue;
			}
#endif


			if (strcmp(message, "connect")==0)
			{
				printf("Enter server ip: ");
				Gets(ip, sizeof(ip));
				if (ip[0]==0)
					strcpy(ip, "127.0.0.1");

				printf("Enter server port: ");				
				Gets(serverPort,sizeof(serverPort));
				if (serverPort[0]==0)
					strcpy(serverPort, "1234");

#if LIBCAT_SECURITY==1
				bool b = client->Connect(ip, atoi(serverPort), "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"), &pk)==RakNet::CONNECTION_ATTEMPT_STARTED;	
#else
				bool b = client->Connect(ip, atoi(serverPort), "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"))==RakNet::CONNECTION_ATTEMPT_STARTED;	
#endif

				if (b)
					puts("Attempting connection");
				else
				{
					puts("Bad connection attempt.  Terminating.");
					exit(1);
				}
				continue;
			}

			if (strcmp(message, "ping")==0)
			{
				if (client->GetSystemAddressFromIndex(0)!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
					client->Ping(client->GetSystemAddressFromIndex(0));

				continue;
			}

			if (strcmp(message, "getlastping")==0)
			{
				if (client->GetSystemAddressFromIndex(0)!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
					printf("Last ping is %i\n", client->GetLastPing(client->GetSystemAddressFromIndex(0)));

				continue;
			}

			// message is the data to send
			// strlen(message)+1 is to send the null terminator
			// HIGH_PRIORITY doesn't actually matter here because we don't use any other priority
			// RELIABLE_ORDERED means make sure the message arrives in the right order
			client->Send(message, (int) strlen(message)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
		}

		// Get a packet from either the server or the client

		for (p=client->Receive(); p; client->DeallocatePacket(p), p=client->Receive())
		{
			// We got a packet, get the identifier with our handy function
			packetIdentifier = GetPacketIdentifier(p);

			// Check if this is a network message packet
			switch (packetIdentifier)
			{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_ALREADY_CONNECTED:
				// Connection lost normally
				printf("ID_ALREADY_CONNECTED with guid %" PRINTF_64_BIT_MODIFIER "u\n", p->guid);
				break;
			case ID_INCOMPATIBLE_PROTOCOL_VERSION:
				printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
				break;
			case ID_REMOTE_DISCONNECTION_NOTIFICATION: // Server telling the clients of another client disconnecting gracefully.  You can manually broadcast this in a peer to peer enviroment if you want.
				printf("ID_REMOTE_DISCONNECTION_NOTIFICATION\n"); 
				break;
			case ID_REMOTE_CONNECTION_LOST: // Server telling the clients of another client disconnecting forcefully.  You can manually broadcast this in a peer to peer enviroment if you want.
				printf("ID_REMOTE_CONNECTION_LOST\n");
				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION: // Server telling the clients of another client connecting.  You can manually broadcast this in a peer to peer enviroment if you want.
				printf("ID_REMOTE_NEW_INCOMING_CONNECTION\n");
				break;
			case ID_CONNECTION_BANNED: // Banned from this server
				printf("We are banned from this server.\n");
				break;			
			case ID_CONNECTION_ATTEMPT_FAILED:
				printf("Connection attempt failed\n");
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				// Sorry, the server is full.  I don't do anything here but
				// A real app should tell the user
				printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
				break;

			case ID_INVALID_PASSWORD:
				printf("ID_INVALID_PASSWORD\n");
				break;

			case ID_CONNECTION_LOST:
				// Couldn't deliver a reliable packet - i.e. the other system was abnormally
				// terminated
				printf("ID_CONNECTION_LOST\n");
				break;

			case ID_CONNECTION_REQUEST_ACCEPTED:
				// This tells the client they have connected
				printf("ID_CONNECTION_REQUEST_ACCEPTED to %s with GUID %s\n", p->systemAddress.ToString(true), p->guid.ToString());
				printf("My external address is %s\n", client->GetExternalID(p->systemAddress).ToString(true));
				break;
			case ID_CONNECTED_PING:
			case ID_UNCONNECTED_PING:
				printf("Ping from %s\n", p->systemAddress.ToString(true));
				break;
			default:
				// It's a client, so just show the message
				printf("====== %s\n", p->data);
				break;
			}
		}
	}

	// Be nice and let the server know we quit.
	client->Shutdown(300);

	// We're done with the network
	RakNet::RakPeerInterface::DestroyInstance(client);

	return 0;
}
Пример #13
0
int main(void)
{

	printf("A sample on how to use RakVoice together with DirectSound.\n");
	printf("You need a microphone for this sample.\n");
	printf("RakVoice relies on Speex for voice encoding and decoding.\n");
	printf("See DependentExtensions/RakVoice/speex-1.2beta3 for speex projects.\n");
	printf("For windows, I had to define HAVE_CONFIG_H, include win32/config.h,\n");
	printf("and include the files under libspeex, except those that start with test.\n");
	printf("Difficulty: Advanced\n\n");

	bool mute=false;
	bool quit;
	char ch;

	char port[256];
	rakPeer = RakNet::RakPeerInterface::GetInstance();
#if defined(INTERACTIVE)
	printf("Enter local port: ");
	Gets(port, sizeof(port));
	if (port[0]==0)
#endif
		strcpy(port, "60000");
	RakNet::SocketDescriptor socketDescriptor(atoi(port),0);

	rakPeer->Startup(4, &socketDescriptor, 1);

	rakPeer->SetMaximumIncomingConnections(4);
	rakPeer->AttachPlugin(&rakVoice);

	rakVoice.Init(SAMPLE_RATE, FRAMES_PER_BUFFER*sizeof(SAMPLE));

	// Initialize our connection with DirectSound
	if (!RakNet::DSoundVoiceAdapter::Instance()->SetupAdapter(&rakVoice, GetConsoleHwnd(), DSSCL_EXCLUSIVE))
	{
		printf("An error occurred while initializing DirectSound.\n");
		exit(-1);
	}

	RakNet::Packet *p;
	quit=false;
#if defined(INTERACTIVE)
	printf("(Q)uit. (C)onnect. (D)isconnect. (M)ute. ' ' for stats.\n");
	printf("(+/-)encoder complexity.  (N)oise filter on/off. (V)AD on/off. (B)vbr on/off.\n");
#else
	rakPeer->Connect("1.1.1.1", 60000, 0,0);
#endif
	PrintParameters();
	while (!quit)
	{
#if defined(INTERACTIVE)
		if (kbhit())
		{
			ch=getch();
			if (ch=='+'){
				// Increase encoder complexity
				int v = rakVoice.GetEncoderComplexity();
				if (v<10) rakVoice.SetEncoderComplexity(v+1);
				PrintParameters();
			}
			else if (ch=='-'){
				// Decrease encoder complexity
				int v = rakVoice.GetEncoderComplexity();
				if (v>0) rakVoice.SetEncoderComplexity(v-1);
				PrintParameters();
			}
			else if (ch=='n'){
				// Turn on/off noise filter
				rakVoice.SetNoiseFilter(!rakVoice.IsNoiseFilterActive());
				PrintParameters();
			}
			else if (ch=='v') {
				// Turn on/off Voice detection
				rakVoice.SetVAD(!rakVoice.IsVADActive());
				PrintParameters();
			}
			else if (ch=='b') {
				// Turn on/off VBR
				rakVoice.SetVBR(!rakVoice.IsVBRActive());
				PrintParameters();
			}
			else if (ch=='y')
			{
				quit=true;
			}
			else if (ch=='c')
			{
				char ip[256];
				printf("\nEnter IP of remote system: ");
				Gets(ip, sizeof(ip));
				if (ip[0]==0)
					strcpy(ip, "127.0.0.1");
				printf("\nEnter port of remote system: ");
				Gets(port, sizeof(port));
				if (port[0]==0)
					strcpy(port, "60000");
				rakPeer->Connect(ip, atoi(port), 0,0);
			}
			else if (ch=='m')
			{
				mute=!mute;
				RakNet::DSoundVoiceAdapter::Instance()->SetMute(mute);
				if (mute)
					printf("\nNow muted.\n");
				else
					printf("\nNo longer muted.\n");
			}
			else if (ch=='d')
			{
				rakPeer->Shutdown(100,0);
			}
			else if (ch==' ')
			{
				char message[2048];
				RakNet::RakNetStatistics *rss=rakPeer->GetStatistics(rakPeer->GetSystemAddressFromIndex(0));
				StatisticsToString(rss, message, 2);
				printf("%s", message);
			}
			else if (ch=='q')
				quit=true;
			ch=0;
		}

#endif

		p=rakPeer->Receive();
		while (p)
		{
			if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{
				printf("\nID_CONNECTION_REQUEST_ACCEPTED from %s\n", p->systemAddress.ToString());
				rakVoice.RequestVoiceChannel(p->guid);
			}
			else if (p->data[0]==ID_RAKVOICE_OPEN_CHANNEL_REQUEST)
			{
				printf("\nOpen Channel request from %s\n", p->systemAddress.ToString());
			}
			else if (p->data[0]==ID_RAKVOICE_OPEN_CHANNEL_REPLY)
			{
				printf("\nGot new channel from %s\n", p->systemAddress.ToString());
			}

			rakPeer->DeallocatePacket(p);
			p=rakPeer->Receive();
		}
		
		// Update our connection with DirectSound
		RakNet::DSoundVoiceAdapter::Instance()->Update();

		LogStats();
		RakSleep(20);
	}

	// Release any FMOD resources we used, and shutdown FMOD itself
	RakNet::DSoundVoiceAdapter::Instance()->Release();

	rakPeer->Shutdown(300);
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);

	return 0;
}
void main(void)
{
	printf("The 2nd interation of the lobby server.\n");
	printf("Difficulty: Intermediate\n\n");

	char serverPort[30];
	RakNet::RakPeerInterface *rakPeer=RakNet::RakPeerInterface::GetInstance();
	rakPeer->SetTimeoutTime(5000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
	//rakPeer->SetTimeoutTime(3000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
	puts("Enter the rakPeer port to listen on");
	serverPort[0]=0;
	Gets(serverPort,sizeof(serverPort));
	if (serverPort[0]==0)
		strcpy(serverPort, "61111");

	RakNet::SocketDescriptor socketDescriptor(atoi(serverPort),0);
	rakPeer->SetMaximumIncomingConnections(32);
	if (rakPeer->Startup(32,&socketDescriptor, 1)!=RakNet::RAKNET_STARTED)
	{
		printf("Startup call failed\n");
		return;
	}
	else
		printf("Started on port %i\n", socketDescriptor.port);
	// Attach the plugin Lobby2Server
	// The class factory will create messages with server functionality
	RakNet::Lobby2Server_PGSQL lobby2Server;
	rakPeer->AttachPlugin(&lobby2Server);
	RakNet::Lobby2MessageFactory_PGSQL messageFactory;
	lobby2Server.SetMessageFactory(&messageFactory);

	// This is optional:
#ifdef __INTEGRATE_LOBBY2_WITH_ROOMS_PLUGIN
	RakNet::RoomsPlugin roomsPluginServer;
	rakPeer->AttachPlugin(&roomsPluginServer);
	lobby2Server.SetRoomsPlugin(&roomsPluginServer);
	RakNet::ProfanityFilter profanityFilter;
	profanityFilter.AddWord("Penis");
	roomsPluginServer.SetProfanityFilter(&profanityFilter);
	roomsPluginServer.roomsContainer.AddTitle("Test Title Name");
#endif

	printf("Enter database password:\n");
	char connectionString[256],password[128];
	char username[256];
	strcpy(username, "postgres");
	password[0]=0;
	Gets(password,sizeof(password));
	if (password[0]==0) strcpy(password, "aaaa");
	strcpy(connectionString, "user="******" password="******"Database connection failed\n");
		return;
	}

	printf("Lobby2Server started and waiting for connections\n");


	RakNet::Lobby2Server::ConfigurationProperties c;
	c.requiresEmailAddressValidationToLogin=false;
	c.requiresTitleToLogin=true;
	c.accountRegistrationRequiresCDKey=false;
	c.accountRegistrationRequiredAgeYears=0;
	lobby2Server.SetConfigurationProperties(c);

#ifdef _ALSO_ACT_AS_NAT_PUNCH_SERVER
	RakNet::NatPunchthroughServer natPunchthroughServer;
	RakNet::UDPProxyCoordinator udpProxyCoordinator;
	RakNet::UDPProxyServer udpProxyServer;
	RakNet::NatTypeDetectionServer natTypeDetectionServer;
	udpProxyCoordinator.SetRemoteLoginPassword(COORDINATOR_PASSWORD);
	rakPeer->AttachPlugin(&natPunchthroughServer);
	rakPeer->AttachPlugin(&udpProxyServer);
	rakPeer->AttachPlugin(&udpProxyCoordinator);
	rakPeer->AttachPlugin(&natTypeDetectionServer);
	char ipListStr[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ][ 128 ];
	RakNet::SystemAddress ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ];
	for (int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++)
		ipList[i].ToString(false,ipListStr[i]);
	RakNet::SocketLayer::GetMyIP( ipList );
	natTypeDetectionServer.Startup(ipListStr[1], ipListStr[2], ipListStr[3]);
	// Login proxy server to proxy coordinator
	// Normally the proxy server is on a different computer. Here, we login to our own IP address since the plugin is on the same system

	// This makes it take high CPU usage, comment out of not wanted
	udpProxyServer.LoginToCoordinator(COORDINATOR_PASSWORD, rakPeer->GetMyBoundAddress());
#endif

	RakNet::Packet *packet;
	// Loop for input
	while (1)
	{
		for (packet=rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet=rakPeer->Receive())
		{
			switch (packet->data[0])
			{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_NEW_INCOMING_CONNECTION:
				// Connection lost normally
				printf("ID_NEW_INCOMING_CONNECTION\n");
				printf("Allowing all operations from remote client for testing (insecure)\n");
				printf("Use Lobby2Server::ExecuteCommand for local server operations\n");
				// For this test, allow all operations
				lobby2Server.AddAdminAddress(packet->systemAddress);
				lobby2Server.AddRankingAddress(packet->systemAddress);
				break;
			case ID_CONNECTION_LOST:
				// Couldn't deliver a reliable packet - i.e. the other system was abnormally
				// terminated
				printf("ID_CONNECTION_LOST\n");
				break;
			}
		}

		// This sleep keeps RakNet responsive
		RakSleep(30);

		//printf("%i ", lobby2Server.GetUsers().Size());
	}

	RakNet::RakPeerInterface::DestroyInstance(rakPeer);
}
Пример #15
0
int main()
{
	printf("This sample demonstrates incrementally sending a file with\n");
	printf("the FileListTransferPlugin. Incremental sends will read and send the.\n");
	printf("file only as needed, rather than putting the whole file in memory.\n");
	printf("This is to support sending large files to many users at the same time.\n");
	printf("Difficulty: Intermediate\n\n");

	TestCB testCB;
	RakNet::FileListTransfer flt1, flt2;
#ifdef USE_TCP
	RakNet::PacketizedTCP tcp1, tcp2;
	#if RAKNET_SUPPORT_IPV6==1
	const bool testInet6=true;
	#else
	const bool testInet6=false;
	#endif
	if (testInet6)
	{
		tcp1.Start(60000,1,-99999,AF_INET6);
		tcp2.Start(60001,1,-99999,AF_INET6);
		tcp2.Connect("::1",60000,false,AF_INET6);
	}
	else
	{
		tcp1.Start(60000,1,-99999,AF_INET);
		tcp2.Start(60001,1,-99999,AF_INET);
		tcp2.Connect("127.0.0.1",60000,false,AF_INET);
	}
	tcp1.AttachPlugin(&flt1);
	tcp2.AttachPlugin(&flt2);
#else
	RakNet::RakPeerInterface *peer1 = RakNet::RakPeerInterface::GetInstance();
	RakNet::RakPeerInterface *peer2 = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor sd1(60000,0),sd2(60001,0);
	peer1->Startup(1,&sd1,1);
	peer2->Startup(1,&sd2,1);
	peer1->SetMaximumIncomingConnections(1);
	peer2->Connect("127.0.0.1",60000,0,0,0);
	peer1->AttachPlugin(&flt1);
	peer2->AttachPlugin(&flt2);
	peer1->SetSplitMessageProgressInterval(9);
	peer2->SetSplitMessageProgressInterval(9);
#endif
	// Print sending progress notifications
	flt1.AddCallback(&testFileListProgress);
	// Run incremental reads in a thread so the read does not block the main thread
	flt1.StartIncrementalReadThreads(1);
	RakNet::FileList fileList;
	RakNet::IncrementalReadInterface incrementalReadInterface;
	printf("Enter complete filename with path to test:\n");
	char str[256];
	Gets(str, sizeof(str));
	if (str[0]==0)
		strcpy(str, "D:\\RakNet\\Lib\\RakNetLibStaticDebug.lib");
	file=str;
	fileCopy=file+"_copy";
	// Reference this file, rather than add it in memory. Will send 1000 byte chunks. The reason to do this is so the whole file does not have to be in memory at once
	unsigned int fileLength = GetFileLength(file.C_String());
	if (fileLength==0)
	{
		printf("Test file %s not found.\n", file.C_String());

#ifdef USE_TCP
#else
		RakNet::RakPeerInterface::DestroyInstance(peer1);
		RakNet::RakPeerInterface::DestroyInstance(peer2);
#endif
		return 1;
	}
	fileList.AddFile(file.C_String(), file.C_String(), 0, fileLength, fileLength, FileListNodeContext(0,0), true);
	// Wait for the connection
	printf("File added.\n");
	RakSleep(100);
	RakNet::Packet *packet1, *packet2;
	while (1)
	{
#ifdef USE_TCP
		RakNet::SystemAddress sa;
		sa=tcp2.HasCompletedConnectionAttempt();
		if (sa!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
		{
			flt2.SetupReceive(&testCB, false, sa);
			break;
		}
#else
		// Wait for the connection request to be accepted
		packet2=peer2->Receive();
		if (packet2 && packet2->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
		{
			flt2.SetupReceive(&testCB, false, packet2->systemAddress);
			peer2->DeallocatePacket(packet2);
			break;
		}
		peer2->DeallocatePacket(packet2);
#endif
		RakSleep(30);
	}

	// When connected, send the file. Since the file is a reference, it will be sent incrementally
	while (1)
	{
#ifdef USE_TCP
		packet1=tcp1.Receive();
		packet2=tcp2.Receive();
		RakNet::SystemAddress sa;
		sa = tcp1.HasNewIncomingConnection();
		if (sa!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			flt1.Send(&fileList,0,sa,0,HIGH_PRIORITY,0, &incrementalReadInterface, 2000 * 1024);
		tcp1.DeallocatePacket(packet1);
		tcp2.DeallocatePacket(packet2);
#else
		packet1=peer1->Receive();
		packet2=peer2->Receive();
		if (packet1 && packet1->data[0]==ID_NEW_INCOMING_CONNECTION)
			flt1.Send(&fileList,peer1,packet1->systemAddress,0,HIGH_PRIORITY,0, &incrementalReadInterface, 2000000);
		
		peer1->DeallocatePacket(packet1);
		peer2->DeallocatePacket(packet2);

#endif
		RakSleep(0);
	}
	
#ifdef USE_TCP
#else
	RakNet::RakPeerInterface::DestroyInstance(peer1);
	RakNet::RakPeerInterface::DestroyInstance(peer1);
#endif


	return 0;
}
Пример #16
0
int main(void)
{
	// Pointers to the interfaces of our server and client.
	// Note we can easily have both in the same program
	RakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();
	RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();

	int i = server->GetNumberOfAddresses();

	// Holds packets
	RakNet::Packet* p;

	// Record the first client that connects to us so we can pass it to the ping function
	RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
	bool packetFromServer;
	char portstring[30];

	printf("This is a sample of how to send offline pings and get offline ping\n");
	printf("responses.\n");
	printf("Difficulty: Beginner\n\n");

	// A server
	puts("Enter the server port to listen on");
	Gets(portstring,sizeof(portstring));
	if (portstring[0]==0)
		strcpy(portstring,"60000");

	// Enumeration data
	puts("Enter offline ping response data (for return by a LAN discovery for example)");
	puts("Hit enter for none.");
	char enumData[512];
	Gets(enumData,sizeof(enumData));
	if (enumData[0])
		server->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1);

	puts("Starting server.");

	// The server has to be started to respond to pings.
	RakNet::SocketDescriptor socketDescriptor(atoi(portstring),0);
	bool b = server->Startup(2, &socketDescriptor, 1)==RakNet::RAKNET_STARTED;
	server->SetMaximumIncomingConnections(2);
	if (b)
		puts("Server started, waiting for connections.");
	else
	{ 
		puts("Server failed to start.  Terminating.");
		exit(1);
	}

	socketDescriptor.port=0;
	client->Startup(1,&socketDescriptor, 1);

	puts("'q' to quit, any other key to send a ping from the client.");
	char buff[256];

	// Loop for input
	while (1)
	{
		if (kbhit())
		{
			// Holds user data
			char ip[64], serverPort[30], clientPort[30];

			if (Gets(buff,sizeof(buff))&&(buff[0]=='q'))
				break;
			else
			{

				// Get our input
				puts("Enter the client port to listen on, or 0");
				Gets(clientPort,sizeof(clientPort));
				if (clientPort[0]==0)
					strcpy(clientPort, "0");
				puts("Enter IP to ping");
				Gets(ip, sizeof(ip));
				if (ip[0]==0)
					strcpy(ip, "127.0.0.1");
				puts("Enter the port to ping");
				Gets(serverPort,sizeof(serverPort));
				if (serverPort[0]==0)
					strcpy(serverPort, "60000");

				client->Ping(ip, atoi(serverPort), false);

				puts("Pinging");
			}
		}

		// Get a packet from either the server or the client
		p = server->Receive();

		if (p==0)
		{
			packetFromServer=false;
			p = client->Receive();
		}
		else
			packetFromServer=true;

		if (p==0)
			continue;


		// Check if this is a network message packet
		switch (p->data[0])
		{
			case ID_UNCONNECTED_PONG:
				{
					unsigned int dataLength;
					RakNet::TimeMS time;
					RakNet::BitStream bsIn(p->data,p->length,false);
					bsIn.IgnoreBytes(1);
					bsIn.Read(time);
					dataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS);
					printf("ID_UNCONNECTED_PONG from SystemAddress %s.\n", p->systemAddress.ToString(true));
					printf("Time is %i\n",time);
					printf("Ping is %i\n", (unsigned int)(RakNet::GetTimeMS()-time));
					printf("Data is %i bytes long.\n", dataLength);
					if (dataLength > 0)
						printf("Data is %s\n", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS));

					// In this sample since the client is not running a game we can save CPU cycles by
					// Stopping the network threads after receiving the pong.
					client->Shutdown(100);
				}
				break;
			case ID_UNCONNECTED_PING:
				break;
			case ID_UNCONNECTED_PING_OPEN_CONNECTIONS:
				break;			
		}

		// We're done with the packet
		if (packetFromServer)
			server->DeallocatePacket(p);
		else
			client->DeallocatePacket(p);
	}

	// We're done with the network
	RakNet::RakPeerInterface::DestroyInstance(server);
	RakNet::RakPeerInterface::DestroyInstance(client);

	return 0;
}
int main()
{
	printf("This sample creates two Lobby2Clients.\n");
	printf("They both connect to the server and performs queued operations on startup.");
	printf("(RANKING AND CLANS NOT YET DONE).\n");
	printf("Difficulty: Advanced\n\n");

	RakNet::Lobby2ResultCodeDescription::Validate();

	/// Do all these operations in this order once we are logged in.
	/// This is for easier testing.
	/// This plan will create the database, register two users, and log them both in
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_CreateDatabase), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_CreateTitle), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_CDKey_Add), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_RegisterProfanity), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_RegisterAccount), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_RegisterAccount), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_SetEmailAddressValidated), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_System_SetEmailAddressValidated), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_Login), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_Login), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Emails_Send), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Emails_Get), _FILE_AND_LINE_ );
// 	/// Create 2 clans
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	// Invite to both
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_RejectJoinInvitation), _FILE_AND_LINE_ );
// 	// Download invitations this clan has sent
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_DownloadInvitationList), _FILE_AND_LINE_ );

	/*

	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_SetPresence), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_GetAccountDetails), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_PerTitleIntegerStorage), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_PerTitleIntegerStorage), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_StartIgnore), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_GetIgnoreList), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Friends_SendInvite), _FILE_AND_LINE_);
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Friends_AcceptInvite), _FILE_AND_LINE_);

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_SubmitMatch));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_SubmitMatch));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_UpdateRating));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_GetRating));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_WipeRatings));
	*/
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Get), _FILE_AND_LINE_ );
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetProperties));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetMyMemberProperties));
	*/
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_WithdrawJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_DownloadInvitationList));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_RejectJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_AcceptJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetSubleaderStatus));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetMemberRank));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GrantLeader));
	*/

	/*
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_WithdrawJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	*/

//	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
//	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_DownloadRequestList));
	// TODO - test from here
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_RejectJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_KickAndBlacklistUser));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GetBlacklist));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_UnblacklistUser));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GetMembers));
	*/

	/*
	// TODO
	L2MID_Clans_CreateBoard,
		L2MID_Clans_DestroyBoard,
		L2MID_Clans_CreateNewTopic,
		L2MID_Clans_ReplyToTopic,
		L2MID_Clans_RemovePost,
		L2MID_Clans_GetBoards,
		L2MID_Clans_GetTopics,
		L2MID_Clans_GetPosts,
		*/
	

	char ip[64], serverPort[30], clientPort[30];
	int i;
	for (i=0; i < NUM_CONNECTIONS; i++)
		rakPeer[i]=RakNet::RakPeerInterface::GetInstance();
	puts("Enter the rakPeer1 port to listen on");
	clientPort[0]=0;
	RakNet::SocketDescriptor socketDescriptor(atoi(clientPort),0);
	Gets(clientPort,sizeof(clientPort));
	if (clientPort[0]==0)
		strcpy(clientPort, "0");

	puts("Enter IP to connect to");;
	ip[0]=0;
	Gets(ip,sizeof(ip));
	if (ip[0]==0)
		strcpy(ip, "127.0.0.1");

	puts("Enter the port to connect to");
	serverPort[0]=0;
	Gets(serverPort,sizeof(serverPort));
	if (serverPort[0]==0)
		strcpy(serverPort, "61111");

	for (i=0; i < NUM_CONNECTIONS; i++)
	{
		rakPeer[i]->Startup(1,&socketDescriptor, 1);
		rakPeer[i]->Connect(ip, atoi(serverPort), 0,0);

		rakPeer[i]->AttachPlugin(&lobby2Client[i]);
		lobby2Client[i].SetMessageFactory(&messageFactory);
		lobby2Client[i].SetCallbackInterface(&callback[i]);
		testUserName[i]=RakNet::RakString("user%i", i);
	}

	RakNet::Packet *packet;
	// Loop for input
	while (1)
	{
		for (i=0; i < NUM_CONNECTIONS; i++)
		{
			RakNet::RakPeerInterface *peer = rakPeer[i];
			for (packet=peer->Receive(); packet; peer->DeallocatePacket(packet), packet=peer->Receive())
			{
				switch (packet->data[0])
				{
				case ID_DISCONNECTION_NOTIFICATION:
					// Connection lost normally
					printf("ID_DISCONNECTION_NOTIFICATION\n");
					break;
				case ID_ALREADY_CONNECTED:
					// Connection lost normally
					printf("ID_ALREADY_CONNECTED\n");
					break;
				case ID_CONNECTION_BANNED: // Banned from this server
					printf("We are banned from this server.\n");
					break;			
				case ID_CONNECTION_ATTEMPT_FAILED:
					printf("Connection attempt failed\n");
					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					// Sorry, the server is full.  I don't do anything here but
					// A real app should tell the user
					printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
					break;
				case ID_INVALID_PASSWORD:
					printf("ID_INVALID_PASSWORD\n");
					break;
				case ID_CONNECTION_LOST:
					// Couldn't deliver a reliable packet - i.e. the other system was abnormally
					// terminated
					printf("ID_CONNECTION_LOST\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					// This tells the rakPeer1 they have connected
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
					int j;
					for (j=0; j < NUM_CONNECTIONS; j++)
						lobby2Client[j].SetServerAddress(packet->systemAddress);
					if (i==NUM_CONNECTIONS-1)
					{
						PrintCommands(&messageFactory);
						printf("Enter instance number 1 to %i followed by command number.\n", NUM_CONNECTIONS);

						if (executionPlan.Size())
						{
							/// Execute the first command now that both clients have connected.
							AutoExecutionPlanNode aepn = executionPlan.Pop();
							ExecuteCommand(aepn.operation, RakNet::RakString("user%i", aepn.instanceNumber), aepn.instanceNumber);
						}
					}
					break;
				case ID_LOBBY2_SERVER_ERROR:
					{
						RakNet::BitStream bs(packet->data,packet->length,false);
						bs.IgnoreBytes(2); // ID_LOBBY2_SERVER_ERROR and error code
						printf("ID_LOBBY2_SERVER_ERROR: ");
						if (packet->data[1]==RakNet::L2SE_UNKNOWN_MESSAGE_ID)
						{
							unsigned int messageId;
							bs.Read(messageId);
							printf("L2SE_UNKNOWN_MESSAGE_ID %i", messageId);
						}
						else
							printf("Unknown");
						printf("\n");				
					}

					break;
				}
			}
		}
		
		
		// This sleep keeps RakNet responsive
		RakSleep(30);

		if (kbhit())
		{
			char ch = getch();
			if (ch <= '0' || ch > '9')
			{
				printf("Bad instance number\n");
				continue;
			}
			int instanceNumber = ch - 1 - '0';
			if (instanceNumber >= NUM_CONNECTIONS)
			{
				printf("Enter between 1 and %i to pick the instance of RakPeer to run\n", 1+NUM_CONNECTIONS);
				continue;
			}

			printf("Enter message number or 'quit' to quit.\n");
			char str[128];
			Gets(str, sizeof(str));
			if (_stricmp(str, "quit")==0)
			{
				printf("Quitting.\n");
				break;
			}
			else
			{
				int command = atoi(str);
				if (command <=0 || command > RakNet::L2MID_COUNT)
				{
					printf("Invalid message index %i. Commands:\n", command);
					PrintCommands(&messageFactory);
				}
				else
				{
					ExecuteCommand((RakNet::Lobby2MessageID)(command-1), RakNet::RakString("user%i", instanceNumber), instanceNumber);
				}
			}
		}
	}

	for (i=0; i < NUM_CONNECTIONS; i++)
		RakNet::RakPeerInterface::DestroyInstance(rakPeer[i]);
	return 0;
}
Пример #18
0
int main(int argc, char** argv) {
	RakNet::RakPeerInterface *server = RakNet::RakPeerInterface::GetInstance();
	RakNet::Packet* p;
	unsigned char packetIdentifier;
	RakNet::SystemAddress clientID = RakNet::UNASSIGNED_SYSTEM_ADDRESS;
	RakNet::RakNetStatistics *rss;
	RakNet::SocketDescriptor socketDescriptors[2];
	char portstring[30];

	socketDescriptors[0].port = SERVER_PORT;
	socketDescriptors[0].socketFamily = AF_INET; // Test out IPV4
	socketDescriptors[1].port = SERVER_PORT;
	socketDescriptors[1].socketFamily = AF_INET6; // Test out IPV6
	if (server->Startup(4, socketDescriptors, 2) != RakNet::RAKNET_STARTED) {
		std::cout << "IPV6 not supported, starting with IPV4-only interface..." << std::endl;
		if (server->Startup(4, socketDescriptors, 1) != RakNet::RAKNET_STARTED) {
			std::cerr << "Error creating server, exiting..." << std::endl;
			exit(-1);
		}
	}
	std::cout << "Server started successfully. Listening on port " << SERVER_PORT << std::endl;
	server->SetMaximumIncomingConnections(20);
	server->SetOccasionalPing(true);
	server->SetUnreliableTimeout(1000);

	DataStructures::List<RakNet::RakNetSocket2*> sockets;
	server->GetSockets(sockets);
	std::cout << "Socket addresses used by RakNet:" << std::endl;
	for (unsigned int i = 0; i < sockets.Size(); i++) {
		printf("%i. %s\n", i + 1, sockets[i]->GetBoundAddress().ToString(true));
	}
	char message[2048];

	// Loop for input
	while (1)
	{

		// This sleep keeps RakNet responsive
		RakSleep(30);

		if (kbhit())
		{
			// Notice what is not here: something to keep our network running.  It's
			// fine to block on gets or anything we want
			// Because the network engine was painstakingly written using threads.
			Gets(message, sizeof(message));

			if (strcmp(message, "quit") == 0)
			{
				puts("Quitting.");
				break;
			}

			if (strcmp(message, "stat") == 0)
			{
				rss = server->GetStatistics(server->GetSystemAddressFromIndex(0));
				StatisticsToString(rss, message, 2);
				printf("%s", message);
				printf("Ping %i\n", server->GetAveragePing(server->GetSystemAddressFromIndex(0)));

				continue;
			}

			if (strcmp(message, "ping") == 0)
			{
				server->Ping(clientID);

				continue;
			}

			if (strcmp(message, "pingip") == 0)
			{
				printf("Enter IP: ");
				Gets(message, sizeof(message));
				printf("Enter port: ");
				Gets(portstring, sizeof(portstring));
				if (portstring[0] == 0)
					strcpy(portstring, "1234");
				server->Ping(message, atoi(portstring), false);

				continue;
			}

			if (strcmp(message, "kick") == 0)
			{
				server->CloseConnection(clientID, true, 0);

				continue;
			}

			if (strcmp(message, "getconnectionlist") == 0)
			{
				printf("Connections:\n");
				RakNet::SystemAddress systems[10];
				unsigned short numConnections = 10;
				server->GetConnectionList((RakNet::SystemAddress*) &systems, &numConnections);
				for (int i = 0; i < numConnections; i++)
				{
					printf("%i. %s\n", i + 1, systems[i].ToString(true));
				}
				continue;
			}

			if (strcmp(message, "ban") == 0)
			{
				printf("Enter IP to ban.  You can use * as a wildcard\n");
				Gets(message, sizeof(message));
				server->AddToBanList(message);
				printf("IP %s added to ban list.\n", message);

				continue;
			}


			// Message now holds what we want to broadcast
			char message2[2048];
			// Append Server: to the message so clients know that it ORIGINATED from the server
			// All messages to all clients come from the server either directly or by being
			// relayed from other clients
			message2[0] = 0;
			const static char prefix[] = "Server: ";
			strncpy(message2, prefix, sizeof(message2));
			strncat(message2, message, sizeof(message2) - strlen(prefix) - 1);

			// message2 is the data to send
			// strlen(message2)+1 is to send the null terminator
			// HIGH_PRIORITY doesn't actually matter here because we don't use any other priority
			// RELIABLE_ORDERED means make sure the message arrives in the right order
			// We arbitrarily pick 0 for the ordering stream
			// RakNet::UNASSIGNED_SYSTEM_ADDRESS means don't exclude anyone from the broadcast
			// true means broadcast the message to everyone connected
			server->Send(message2, (const int)strlen(message2) + 1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
		}

		// Get a packet from either the server or the client

		for (p = server->Receive(); p; server->DeallocatePacket(p), p = server->Receive())
		{
			// We got a packet, get the identifier with our handy function
			packetIdentifier = GetPacketIdentifier(p);

			// Check if this is a network message packet
			switch (packetIdentifier)
			{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				printf("ID_DISCONNECTION_NOTIFICATION from %s\n", p->systemAddress.ToString(true));;
				break;


			case ID_NEW_INCOMING_CONNECTION:
				// Somebody connected.  We have their IP now
				printf("ID_NEW_INCOMING_CONNECTION from %s with GUID %s\n", p->systemAddress.ToString(true), p->guid.ToString());
				clientID = p->systemAddress; // Record the player ID of the client

				printf("Remote internal IDs:\n");
				for (int index = 0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++)
				{
					RakNet::SystemAddress internalId = server->GetInternalID(p->systemAddress, index);
					if (internalId != RakNet::UNASSIGNED_SYSTEM_ADDRESS)
					{
						printf("%i. %s\n", index + 1, internalId.ToString(true));
					}
				}

				break;

			case ID_INCOMPATIBLE_PROTOCOL_VERSION:
				printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
				break;

			case ID_CONNECTED_PING:
			case ID_UNCONNECTED_PING:
				printf("Ping from %s\n", p->systemAddress.ToString(true));
				break;

			case ID_CONNECTION_LOST:
				// Couldn't deliver a reliable packet - i.e. the other system was abnormally
				// terminated
				printf("ID_CONNECTION_LOST from %s\n", p->systemAddress.ToString(true));;
				break;

			default:
				// The server knows the static data of all clients, so we can prefix the message
				// With the name data
				printf("%s\n", p->data);

				// Relay the message.  We prefix the name for other clients.  This demonstrates
				// That messages can be changed on the server before being broadcast
				// Sending is the same as before
				sprintf(message, "%s", p->data);
				server->Send(message, (const int)strlen(message) + 1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->systemAddress, true);

				break;
			}

		}
	}

	server->Shutdown(300);
	// We're done with the network
	RakNet::RakPeerInterface::DestroyInstance(server);


}
Пример #19
0
static int read_config_file(const char *name)
{
	idFile *  fp;
	char *w[MAXWORDS], *cp;
	ToneBank *bank=0;
	int i, j, k, line=0, words;
	static int rcf_count=0;

	if (rcf_count>50)
	{
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
			"Probable source loop in configuration files");
		return (-1);
	}

	if (!(fp=open_file(name, 1, OF_VERBOSE)))
		return -2;
	
	char tokTmp[1024];

	while ( Gets( *fp, tokTmp, 1024 ) )
	{
		
		line++;
		w[words=0]=strtok(tokTmp, " \t\r\n\240");
		if (!w[0] || (*w[0]=='#')) continue;
		while (w[words] && (words < MAXWORDS))
			w[++words]=strtok(0," \t\r\n\240");
		if (!strcmp(w[0], "dir"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: No directory given\n", name, line);
				return -3;
			}
			for (i=1; i<words; i++)
				add_to_pathlist(w[i]);
		}
		else if (!strcmp(w[0], "source"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: No file name given\n", name, line);
				return -4;
			}
			for (i=1; i<words; i++)
			{
				rcf_count++;
				read_config_file(w[i]);
				rcf_count--;
			}
		}
		else if (!strcmp(w[0], "default"))
		{
			if (words != 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
					"%s: line %d: Must specify exactly one patch name\n",
					name, line);
				return -5;
			}
			strncpy(def_instr_name, w[1], 255);
			def_instr_name[255]='\0';
		}
		else if (!strcmp(w[0], "drumset"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: No drum set number given\n", 
					name, line);
				return -6;
			}
			i=atoi(w[1]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
					"%s: line %d: Drum set must be between 0 and 127\n",
					name, line);
				return -7;
			}
			if (!drumset[i])
			{
				drumset[i]=(ToneBank*)safe_malloc(sizeof(ToneBank));
				memset(drumset[i], 0, sizeof(ToneBank));
			}
			bank=drumset[i];
		}
		else if (!strcmp(w[0], "bank"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: No bank number given\n", 
					name, line);
				return -8;
			}
			i=atoi(w[1]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
					"%s: line %d: Tone bank must be between 0 and 127\n",
					name, line);
				return -9;
			}
			if (!tonebank[i])
			{
				tonebank[i]=(ToneBank*)safe_malloc(sizeof(ToneBank));
				memset(tonebank[i], 0, sizeof(ToneBank));
			}
			bank=tonebank[i];
		}
		else {
			if ((words < 2) || (*w[0] < '0' || *w[0] > '9'))
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: syntax error\n", name, line);
				return -10;
			}
			i=atoi(w[0]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: Program must be between 0 and 127\n",
					name, line);
				return -11;
			}
			if (!bank)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
					"%s: line %d: Must specify tone bank or drum set "
					"before assignment\n",
					name, line);
				return -12;
			}
			if (bank->tone[i].name)
				Real_Tim_Free(bank->tone[i].name);
			strcpy((bank->tone[i].name=(char*)safe_malloc(strlen(w[1])+1)),w[1]);
			bank->tone[i].note=bank->tone[i].amp=bank->tone[i].pan=
				bank->tone[i].strip_loop=bank->tone[i].strip_envelope=
				bank->tone[i].strip_tail=-1;

			for (j=2; j<words; j++)
			{
				if (!(cp=strchr(w[j], '=')))
				{
					ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
						name, line, w[j]);
					return -13;
				}
				*cp++=0;
				if (!strcmp(w[j], "amp"))
				{
					k=atoi(cp);
					if ((k<0 || k>MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9'))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
							"%s: line %d: amplification must be between "
							"0 and %d\n", name, line, MAX_AMPLIFICATION);
						return -14;
					}
					bank->tone[i].amp=k;
				}
				else if (!strcmp(w[j], "note"))
				{
					k=atoi(cp);
					if ((k<0 || k>127) || (*cp < '0' || *cp > '9'))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
							"%s: line %d: note must be between 0 and 127\n",
							name, line);
						return -15;
					}
					bank->tone[i].note=k;
				}
				else if (!strcmp(w[j], "pan"))
				{
					if (!strcmp(cp, "center"))
						k=64;
					else if (!strcmp(cp, "left"))
						k=0;
					else if (!strcmp(cp, "right"))
						k=127;
					else
						k=((atoi(cp)+100) * 100) / 157;
					if ((k<0 || k>127) ||
						(k==0 && *cp!='-' && (*cp < '0' || *cp > '9')))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
							"%s: line %d: panning must be left, right, "
							"center, or between -100 and 100\n",
							name, line);
						return -16;
					}
					bank->tone[i].pan=k;
				}
				else if (!strcmp(w[j], "keep"))
				{
					if (!strcmp(cp, "env"))
						bank->tone[i].strip_envelope=0;
					else if (!strcmp(cp, "loop"))
						bank->tone[i].strip_loop=0;
					else
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
							"%s: line %d: keep must be env or loop\n", name, line);
						return -17;
					}
				}
				else if (!strcmp(w[j], "strip"))
				{
					if (!strcmp(cp, "env"))
						bank->tone[i].strip_envelope=1;
					else if (!strcmp(cp, "loop"))
						bank->tone[i].strip_loop=1;
					else if (!strcmp(cp, "tail"))
						bank->tone[i].strip_tail=1;
					else
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
							"%s: line %d: strip must be env, loop, or tail\n",
							name, line);
						return -18;
					}
				}
				else
				{
					ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
						name, line, w[j]);
					return -19;
				}
			}
		}
	}
	if ( fp == 0 ) //(ferror(fp))
	{
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Can't read from %s\n", name);
		close_file(fp);
		return -20;
	}
	close_file(fp);
	return 0;
}
Пример #20
0
void main(void)
{
	printf("Demonstrates the crash reporter.\n");
	printf("This program will prompt you for a variety of actions to take on crash.\n");
	printf("If so desired, it will generate a minidump which can be opened in visual studio\n");
	printf("to debug the crash.\n\n");

	RakNet::CrashReportControls controls;
	controls.actionToTake=0;

	printf("Send an email? (y/n)\n");
	if (getch()=='y')
	{
		printf("Attach the mini-dump to the email? (y/n)\n");
		if (getch()=='y')
			controls.actionToTake|=RakNet::AOC_EMAIL_WITH_ATTACHMENT;
		else
			controls.actionToTake|=RakNet::AOC_EMAIL_NO_ATTACHMENT;
	}
	printf("Write mini-dump to disk? (y/n)\n");
	if (getch()=='y')
		controls.actionToTake|=RakNet::AOC_WRITE_TO_DISK;
	printf("Handle crashes in silent mode (no prompts)? (y/n)\n");
	if (getch()=='y')
		controls.actionToTake|=RakNet::AOC_SILENT_MODE;

	if ((controls.actionToTake & RakNet::AOC_EMAIL_WITH_ATTACHMENT) || (controls.actionToTake & RakNet::AOC_EMAIL_NO_ATTACHMENT))
	{
		if (controls.actionToTake & RakNet::AOC_SILENT_MODE)
		{
			printf("Enter SMTP Server: ");
			Gets(controls.SMTPServer,sizeof(controls.SMTPServer));
			if (controls.SMTPServer[0]==0)
				return;
			printf("Enter SMTP account name: ");
			Gets(controls.SMTPAccountName,sizeof(controls.SMTPAccountName));
			if (controls.SMTPAccountName[0]==0)
				return;
			printf("Enter sender email address: ");
			Gets(controls.emailSender,sizeof(controls.emailSender));
		}

		printf("Enter email recipient email address: ");
		Gets(controls.emailRecipient,sizeof(controls.emailRecipient));
		if (controls.emailRecipient[0]==0)
			return;

		printf("Enter subject prefix, if any: ");
		Gets(controls.emailSubjectPrefix,sizeof(controls.emailSubjectPrefix));

		if ((controls.actionToTake & RakNet::AOC_SILENT_MODE)==0)
		{
			printf("Enter text to write in email body: ");
			Gets(controls.emailBody,sizeof(controls.emailBody));
		}
	}
	
	if (controls.actionToTake & RakNet::AOC_WRITE_TO_DISK)
	{
		printf("Enter disk path to write to (ENTER for current directory): ");
		Gets(controls.pathToMinidump,sizeof(controls.pathToMinidump));
	}

	printf("Enter application name: ");
	Gets(controls.appName,sizeof(controls.appName));
	printf("Enter application version: ");
	Gets(controls.appVersion,sizeof(controls.appVersion));

	// MiniDumpNormal will not give you SocketLayer::I correctly but is small (like 15K)
	// MiniDumpWithDataSegs is much bigger (391K) but does give you SocketLayer::I correctly.
	controls.minidumpType=MiniDumpWithDataSegs;

	// You must call Start before any crashes will be reported.
	RakNet::CrashReporter::Start(&controls);
	printf("Crash reporter started.\n");

// If you don't plan to debug the crash reporter itself, you can remove the __try within _DEBUG_CRASH_REPORTER
#ifdef _DEBUG_CRASH_REPORTER
	__try 
#endif
	{
		RunGame();
	}

// If you don't plan to debug the crash reporter itself, you can remove the DumpMiniDump code within _DEBUG_CRASH_REPORTER
#ifdef _DEBUG_CRASH_REPORTER
	__except(DumpMiniDump(GetExceptionInformation()),EXCEPTION_EXECUTE_HANDLER) 
	{
	}
#endif
}
Пример #21
0
int main()
{
	printf("TODO Rename RackspaceConsole.\nAdd RackspaceServerManager, uses CloudClient to monitor load, reboot lost servers.\n");

#if OPEN_SSL_CLIENT_SUPPORT!=1
	printf("RakNet must be built with OPEN_SSL_CLIENT_SUPPORT");
	return 1;
#endif

	RakNet::Rackspace rackspaceApi;
	RakNet::TCPInterface tcpInterface;

	DisplayHTMLPage callback;
	rackspaceApi.AddEventCallback(&callback);

	tcpInterface.Start(0, 0, 1);

	if (!Authenticate(&rackspaceApi, &tcpInterface))
	{
		return 1;
	}
	//rackspaceApi.ListImages();

	PrintCommands();

	RakNet::SystemAddress systemAddress;
	RakNet::Packet *packet;
	while (1)
	{
		for (packet=tcpInterface.Receive(); packet; tcpInterface.DeallocatePacket(packet), packet=tcpInterface.Receive())
		{
			rackspaceApi.OnReceive(packet);
		}

		RakNet::SystemAddress lostConnectionAddress = tcpInterface.HasLostConnection();
		if (lostConnectionAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			rackspaceApi.OnClosedConnection(lostConnectionAddress);

		if (kbhit())
		{
			printf("Command: ");

			char command[128];
			Gets(command, sizeof(command));

			if (stricmp(command,"Help")==0)
			{
				PrintCommands();
			}
			else if (stricmp(command,"Quit")==0)
			{
				break;
			}
			else if (stricmp(command,"Authenticate")==0)
			{
				Authenticate(&rackspaceApi, &tcpInterface);
			}
			else if (stricmp(command,"ListServers")==0)
			{
				rackspaceApi.ListServers();
			}
			else if (stricmp(command,"ListServersWithDetails")==0)
			{
				rackspaceApi.ListServersWithDetails();
			}
			else if (stricmp(command,"CreateServer")==0)
			{
				RakNet::RakString name;
				printf("Enter server name: ");
				Gets(command, sizeof(command));
				name=command;
				RakNet::RakString imageId;
				printf("Enter imageId: ");
				Gets(command, sizeof(command));
				imageId=command;
				RakNet::RakString flavorId;
				printf("Enter flavorId: ");
				Gets(command, sizeof(command));
				flavorId=command;

				rackspaceApi.CreateServer(name, imageId, flavorId);
			}
			else if (stricmp(command,"GetServerDetails")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetServerDetails(command);
			}
			else if (stricmp(command,"UpdateServerNameOrPassword")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString newName;
				printf("Enter newName: ");
				Gets(command, sizeof(command));
				newName=command;
				RakNet::RakString newPassword;
				printf("Enter newPassword: "******"DeleteServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteServer(command);
			}
			else if (stricmp(command,"ListServerAddresses")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.ListServerAddresses(command);
			}
			else if (stricmp(command,"ShareServerAddress")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString serverAddress;
				printf("Enter server serverAddress: ");
				Gets(command, sizeof(command));
				serverAddress=command;
				rackspaceApi.ShareServerAddress(serverId, serverAddress);
			}
			else if (stricmp(command,"DeleteServerAddress")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString serverAddress;
				printf("Enter server serverAddress: ");
				Gets(command, sizeof(command));
				serverAddress=command;
				rackspaceApi.DeleteServerAddress(serverId, serverAddress);
			}
			else if (stricmp(command,"RebootServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString rebootType;
				printf("Enter rebootType: ");
				Gets(command, sizeof(command));
				rebootType=command;
				rackspaceApi.RebootServer(serverId,rebootType);
			}
			else if (stricmp(command,"RebuildServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString imageId;
				printf("Enter imageId: ");
				Gets(command, sizeof(command));
				imageId=command;
				rackspaceApi.RebuildServer(serverId,imageId);
			}
			else if (stricmp(command,"ResizeServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString flavorId;
				printf("Enter flavorId: ");
				Gets(command, sizeof(command));
				flavorId=command;
				rackspaceApi.ResizeServer(serverId,flavorId);
			}
			else if (stricmp(command,"ConfirmResizedServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.ConfirmResizedServer(command);
			}
			else if (stricmp(command,"RevertResizedServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.RevertResizedServer(command);
			}
			else if (stricmp(command,"ListFlavors")==0)
			{
				rackspaceApi.ListFlavors();
			}
			else if (stricmp(command,"GetFlavorDetails")==0)
			{
				printf("Enter flavor id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetFlavorDetails(command);
			}
			else if (stricmp(command,"ListImages")==0)
			{
				rackspaceApi.ListImages();
			}
			else if (stricmp(command,"CreateImage")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString imageName;
				printf("Enter imageName: ");
				Gets(command, sizeof(command));
				imageName=command;
				rackspaceApi.CreateImage(serverId,imageName);
			}
			else if (stricmp(command,"GetImageDetails")==0)
			{
				printf("Enter image id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetImageDetails(command);
			}
			else if (stricmp(command,"DeleteImage")==0)
			{
				printf("Enter image id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteImage(command);
			}
			else if (stricmp(command,"ListSharedIPGroups")==0)
			{
				rackspaceApi.ListSharedIPGroups();
			}
			else if (stricmp(command,"ListSharedIPGroupsWithDetails")==0)
			{
				rackspaceApi.ListSharedIPGroupsWithDetails();
			}
			else if (stricmp(command,"CreateSharedIPGroup")==0)
			{
				rackspaceApi.CreateSharedIPGroup("testSharedIPGroup","");
			}
			else if (stricmp(command,"GetSharedIPGroupDetails")==0)
			{
				printf("Enter group id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetSharedIPGroupDetails(command);
			}
			else if (stricmp(command,"DeleteSharedIPGroup")==0)
			{
				printf("Enter group id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteSharedIPGroup(command);
			}
			else
			{
				printf("Unknown command. Type 'help' for help.\n");
			}
		}

		RakSleep(30);
	}

	return 0;
}
int main(int argc, char **argv)
{
	// Avoids the Error: Got a packet bigger than 'max_allowed_packet' bytes
	printf("Important: Requires that you first set the DB schema and the max packet size on the server.\n");
	printf("See DependentExtensions/AutopatcherMySQLRepository/readme.txt\n");
	// // MySQL is extremely slow in AutopatcherMySQLRepository::GetFilePart
	printf("WARNING: MySQL is an order of magnitude slower than PostgreSQL.\nRecommended you use AutopatcherServer_PostgreSQL instead.");

	printf("Server starting... ");
	RakNet::AutopatcherServer autopatcherServer;
	// RakNet::FLP_Printf progressIndicator;
	RakNet::FileListTransfer fileListTransfer;
	// So only one thread runs per connection, we create an array of connection objects, and tell the autopatcher server to use one thread per item
	static const int workerThreadCount=4; // Used for checking patches only
	static const int sqlConnectionObjectCount=32; // Used for both checking patches and downloading
	RakNet::AutopatcherMySQLRepository connectionObject[sqlConnectionObjectCount];
	RakNet::AutopatcherRepositoryInterface *connectionObjectAddresses[sqlConnectionObjectCount];
	for (int i=0; i < sqlConnectionObjectCount; i++)
		connectionObjectAddresses[i]=&connectionObject[i];
	// fileListTransfer.AddCallback(&progressIndicator);
	autopatcherServer.SetFileListTransferPlugin(&fileListTransfer);
	// MySQL is extremely slow in AutopatcherMySQLRepository::GetFilePart so running tho incremental reads in a thread allows multiple concurrent users to read
	// Without this, only one user would be sent files at a time basically
	fileListTransfer.StartIncrementalReadThreads(sqlConnectionObjectCount);
	autopatcherServer.SetMaxConurrentUsers(MAX_INCOMING_CONNECTIONS); // More users than this get queued up
	RakNet::AutopatcherServerLoadNotifier_Printf loadNotifier;
	autopatcherServer.SetLoadManagementCallback(&loadNotifier);
#ifdef USE_TCP
	RakNet::PacketizedTCP packetizedTCP;
	if (packetizedTCP.Start(LISTEN_PORT,MAX_INCOMING_CONNECTIONS)==false)
	{
		printf("Failed to start TCP. Is the port already in use?");
		return 1;
	}
	packetizedTCP.AttachPlugin(&autopatcherServer);
	packetizedTCP.AttachPlugin(&fileListTransfer);
#else
	RakNet::RakPeerInterface *rakPeer;
	rakPeer = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor socketDescriptor(LISTEN_PORT,0);
	rakPeer->Startup(MAX_INCOMING_CONNECTIONS,&socketDescriptor, 1);
	rakPeer->SetMaximumIncomingConnections(MAX_INCOMING_CONNECTIONS);
	rakPeer->AttachPlugin(&autopatcherServer);
	rakPeer->AttachPlugin(&fileListTransfer);
#endif
	printf("started.\n");

	printf("Enter database password:\n");
	char password[128];
	char username[256];
	strcpy(username, "root");
	Gets(password,sizeof(password));
	if (password[0]==0)
		strcpy(password,"aaaa");
	char db[256];
	printf("Enter DB schema: ");
	// To create the schema, go to the command line client and type create schema autopatcher;
	// You also have to add 
	// max_allowed_packet=128M
	// Where 128 is the maximum size file in megabytes you'll ever add
	// to MySQL\MySQL Server 5.1\my.ini in the [mysqld] section
	// Be sure to restart the service after doing so
	Gets(db,sizeof(db));
	if (db[0]==0)
		strcpy(db,"autopatcher");
	for (int conIdx=0; conIdx < sqlConnectionObjectCount; conIdx++)
	{
		if (!connectionObject[conIdx].Connect("localhost", username, password, db, 0, NULL, 0))
		{
			printf("Database connection failed.\n");
			return 1;
		}
	}
	printf("Database connection suceeded.\n");


	printf("Starting threads\n");
	autopatcherServer.StartThreads(workerThreadCount, sqlConnectionObjectCount, connectionObjectAddresses);
	printf("System ready for connections\n");

	printf("(D)rop database\n(C)reate database.\n(A)dd application\n(U)pdate revision.\n(R)emove application\n(Q)uit\n");

	char ch;
	RakNet::Packet *p;
	while (1)
	{
#ifdef USE_TCP
		RakNet::SystemAddress notificationAddress;
		notificationAddress=packetizedTCP.HasCompletedConnectionAttempt();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
		notificationAddress=packetizedTCP.HasNewIncomingConnection();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_NEW_INCOMING_CONNECTION\n");
		notificationAddress=packetizedTCP.HasLostConnection();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_CONNECTION_LOST\n");

		p=packetizedTCP.Receive();
		while (p)
		{
			packetizedTCP.DeallocatePacket(p);
			p=packetizedTCP.Receive();
		}
#else
		p=rakPeer->Receive();
		while (p)
		{
			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
				printf("ID_NEW_INCOMING_CONNECTION\n");
			else if (p->data[0]==ID_DISCONNECTION_NOTIFICATION)
				printf("ID_DISCONNECTION_NOTIFICATION\n");
			else if (p->data[0]==ID_CONNECTION_LOST)
				printf("ID_CONNECTION_LOST\n");

			rakPeer->DeallocatePacket(p);
			p=rakPeer->Receive();
		}
#endif
		if (kbhit())
		{
			ch=getch();
			if (ch=='q')
				break;
			else if (ch=='c')
			{
				if (connectionObject[0].CreateAutopatcherTables()==false)
					printf("Error: %s\n", connectionObject[0].GetLastError());
				else
					printf("Created\n");
			}
			else if (ch=='d')
			{
				if (connectionObject[0].DestroyAutopatcherTables()==false)
					printf("Error: %s\n", connectionObject[0].GetLastError());
				else
					printf("Destroyed\n");
			}
			else if (ch=='a')
			{
				printf("Enter application name to add: ");
				char appName[512];
				Gets(appName,sizeof(appName));
				if (appName[0]==0)
					strcpy(appName, "TestApp");

				if (connectionObject[0].AddApplication(appName, username)==false)
					printf("Error: %s\n", connectionObject[0].GetLastError());
				else
					printf("Done\n");
			}
			else if (ch=='r')
			{
				printf("Enter application name to remove: ");
				char appName[512];
				Gets(appName,sizeof(appName));
				if (appName[0]==0)
					strcpy(appName, "TestApp");

				if (connectionObject[0].RemoveApplication(appName)==false)
					printf("Error: %s\n", connectionObject[0].GetLastError());
				else
					printf("Done\n");
			}
			else if (ch=='u')
			{
				printf("Enter application name: ");
				char appName[512];
				Gets(appName,sizeof(appName));
				if (appName[0]==0)
					strcpy(appName, "TestApp");

				printf("Enter application directory: ");
				char appDir[512];
				Gets(appDir,sizeof(appName));
				if (appDir[0]==0)
					strcpy(appDir, "C:/temp");

				if (connectionObject[0].UpdateApplicationFiles(appName, appDir, username, 0)==false)
				{
					printf("Error: %s\n", connectionObject[0].GetLastError());
				}
				else
				{
					printf("Update success.\n");
				}
			}
		}

		RakSleep(30);


	}

#ifdef USE_TCP
	packetizedTCP.Stop();
#else
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);
#endif
}
Пример #23
0
int main()
{
	RakNet::Packet *packet;
	RakNet::RakPeerInterface *rakPeer;
	bool isConnected=false;
	rakPeer=RakNet::RakPeerInterface::GetInstance();
	char command[512];
	printf("This sample demonstrates connecting to the command console.\n");
	printf("using the RakNet transport protocol\n");
	printf("It's the equivalent of a secure telnet client\n");
	printf("See the 'CommandConsoleServer' project.\n");
	printf("Difficulty: Intermediate\n\n");

	printf("RakNet secure command console.\n");
	printf("Commands:\n");
	printf("/Connect\n");
	printf("/Disconnect\n");
	printf("/Quit\n");
	printf("Any other command goes to the remote console\n");
	while (1)
	{
		if (kbhit())
		{
			Gets(command,sizeof(command));

			if (stricmp(command, "/quit")==0)
			{
				printf("Goodbye.\n");
				rakPeer->Shutdown(500, 0);
				return 0;
			}
			else if (stricmp(command, "/disconnect")==0)
			{
				if (isConnected)
				{
					rakPeer->Shutdown(500, 0);
					isConnected=false;
					printf("Disconnecting.\n");
				}
				else
				{
					printf("Not currently connected.\n");
				}
			}
			else if (stricmp(command, "/connect")==0)
			{
				if (isConnected)
				{
					printf("Disconnect first.\n");
				}
				else
				{
					char ip[128];
					char remotePort[64];
					char password[512];
					char localPort[64];
					printf("Enter remote IP: ");
					do {
						Gets(ip, sizeof(ip));
					} while(ip[0]==0);
					printf("Enter remote port: ");
					do {
						Gets(remotePort,sizeof(remotePort));
					} while(remotePort[0]==0);
					printf("Enter local port (enter for 0): ");
					Gets(localPort,sizeof(localPort));
					if (localPort[0]==0)
					{
						strcpy(localPort, "0");
					}
					printf("Enter console password (enter for none): ");
					Gets(password,sizeof(password));
					RakNet::SocketDescriptor socketDescriptor((int) atoi(localPort),0);
					if (rakPeer->Startup(1, &socketDescriptor, 1)==RakNet::RAKNET_STARTED)
					{
						int passwordLen;
						if (password[0])
							passwordLen=(int) strlen(password)+1;
						else
							passwordLen=0;
						if (rakPeer->Connect(ip, (int) atoi(remotePort), password, passwordLen)==RakNet::CONNECTION_ATTEMPT_STARTED)
							printf("Connecting...\nNote: if the password is wrong the other system will ignore us.\n");
						else
						{
							printf("Connect call failed.\n");
							rakPeer->Shutdown(0, 0);
						}
					}
					else
						printf("Initialize call failed.\n");					
					
				}				
			}
			else
			{
				if (isConnected)
				{
					RakNet::BitStream str;
					str.Write((unsigned char) ID_TRANSPORT_STRING);
					str.Write(command, (int) strlen(command)+1);
					rakPeer->Send(&str, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
				}
				else
				{
					printf("You must be connected to send commands.\n");
				}
			}
		}

		packet = rakPeer->Receive();
		if (packet)
		{
			switch (packet->data[0])
			{
			case ID_DISCONNECTION_NOTIFICATION:
				printf("The server disconnected us.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_BANNED:
				printf("We are banned from this server.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				printf("Connection attempt failed.\nThe password was wrong or there is no responsive machine at that IP/port.\n");
				isConnected=false;
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				printf("Server is full.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_LOST:
				printf("We lost the connection.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				printf("Connection accepted.\n");
				isConnected=true;
				break;
			case ID_TRANSPORT_STRING:
				printf("%s", packet->data+1);
				break;
			}

			rakPeer->DeallocatePacket(packet);
		}

		// This sleep keeps RakNet responsive
#ifdef _WIN32
		Sleep(30);
#else
		usleep(30 * 1000);
#endif
	}

	return 0;
}
Пример #24
0
EXPORT	void	g_prompt_for_composition_type(
	INIT_DATA	*init)
{
	int	i;
	int	dim = i_intfc(init)->dim;
	char	s[Gets_BUF_SIZE];
	static	Prompt_type ctypes[] = {
	    {"PURE_NON_REACTIVE","PNR",3,{PURE_NON_REACTIVE} },
#if defined(MULTI_COMPONENT)
	    {"MULTI_COMP_NON_REACTIVE","MCNR",4,{MULTI_COMP_NON_REACTIVE}},
#endif /* defined(MULTI_COMPONENT) */
#if defined(COMBUSTION_CODE)
	    {"PTFLAME","PTF",3,{PTFLAME}},
	    {"ZND","ZND",3,ZND},
	    {"TWO_CONSTITUENT_REACTIVE","TCR",3,{TWO_CONSTITUENT_REACTIVE}},
	    {"THINFLAME","THF",3,{THINFLAME}},
#endif /* defined(COMBUSTION_CODE) */
	    {NULL, NULL, 0, {ERROR} }
	};

	material_composition_type(init) = PURE_NON_REACTIVE;
	screen("\nRequest composition type of materials. "
	       "Available types are\n");
	for (i = 0; ctypes[i].prompt != NULL; ++i)
	{
	    screen("\t\t%s (%s",ctypes[i].prompt,ctypes[i].select);
	    if (ctypes[i].type.itype == material_composition_type(init))
	    	screen(", default");
	    screen(")\n");
	}
	screen("\tEnter choice here: ");
	(void) Gets(s);
	if (s[0] != '\0')
	{
	    for (i = 0; ctypes[i].prompt != NULL; ++i)
	    {
	        if (strncasecmp(s,ctypes[i].select,ctypes[i].ncmp) == 0)
	        {
	            material_composition_type(init) = ctypes[i].type.itype;
	            break;
	        }
	    }
	}

        /* NOTE: NumberFloats(init) will be modified in g_compute_sizest() **/
        if(MULTI_COMP_NON_REACTIVE == material_composition_type(init))
        {
            (void) printf("Request for maximum number of composed materials: ");
            (void) Scanf("%d\n",&NumberFloats(init));
	    (void) printf("The maximum number of composed materials is %d\n",
                       NumberFloats(init));
        }
	g_compute_sizest(material_composition_type(init),
			 &StateSize(init),&NumberFloats(init),dim);
        /* This change should be universal */
        if(MULTI_COMP_NON_REACTIVE == material_composition_type(init))
        {
            g_set_sizeof_state(NULL,StateSize(init),NumberFloats(init));
            set_composition_type(material_composition_type(init));
        }
}		/*end g_prompt_for_composition_type*/
Пример #25
0
int main()
{
	printf("A C++ class used to send email, such as for servers.\n");
	printf("TLS support (such as for Gmail) requires OPEN_SSL_CLIENT_SUPPORT to be defined\nin RakNetDefines.h.\n");
	printf("Difficulty: Beginner\n\n");

	RakNet::FileList fileList;
	RakNet::EmailSender emailSender;
	const char *quote = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
//	const char base64Map[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//	char output[1024];
//	emailSender.Base64Encoding(quote, strlen(quote), output, base64Map);
//	printf("%s", output);

	char mailServer[128], senderUsername[128], receiver[128], password[128];
	printf("Tests sending email.\n");
	printf("Enter mail server: ");
	Gets(mailServer,sizeof(mailServer));
	if (mailServer[0]==0)
		strcpy(mailServer, "smtp.gmail.com");
	printf("Enter email account username: "******"*****@*****.**");
	printf("Enter receiver email address: ");
	Gets(receiver,sizeof(receiver));
	if (receiver[0]==0)
		strcpy(receiver, "*****@*****.**");
	printf("Enter password needed to send: ");
	Gets(password,sizeof(password));


	// http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
	unsigned short hostPort;
	if (strcmp(mailServer,"smtp.gmail.com")==0)
		hostPort=465;
	else
		hostPort=25;

	fileList.AddFile("quote.txt", "quote.txt", quote, (const unsigned int) strlen(quote), (const unsigned int) strlen(quote), FileListNodeContext(0,0), false);
	const char *sendResult=emailSender.Send(mailServer,
		hostPort,
		senderUsername,
		receiver,
		senderUsername,
		receiver,
		"Test subject.",
		"Test attachment body :).\n.\n..\n.\n(Should be .,.,..,.)\r\n.\r\n.\r\n..\r\n.\r\n(Should be .,.,..,.)12345\r\n.\r\n",
		&fileList,
		true,
		password);
	if (sendResult!=0)
		printf("Send Failed! %s", sendResult);
	else
		printf("Success (probably).\n");
	printf("Press enter to quit.\n");
	char buff[256];
	Gets(buff,sizeof(buff));

	return 0;
}
Пример #26
0
int main(int argc, char **argv)
{
	printf("A simple client interface for the advanced autopatcher.\n");
	printf("Use DirectoryDeltaTransfer for a simpler version of an autopatcher.\n");
	printf("Difficulty: Intermediate\n\n");

	printf("Client starting...");
	RakNet::SystemAddress serverAddress=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
	RakNet::AutopatcherClient autopatcherClient;
	RakNet::FileListTransfer fileListTransfer;
	autopatcherClient.SetFileListTransferPlugin(&fileListTransfer);
	unsigned short localPort=0;
	if (argc>=6)
	{
		localPort=atoi(argv[5]);
	}
#ifdef USE_TCP
	RakNet::PacketizedTCP packetizedTCP;
	if (packetizedTCP.Start(localPort,1)==false)
	{
		printf("Failed to start TCP. Is the port already in use?");
		return 1;
	}
	packetizedTCP.AttachPlugin(&autopatcherClient);
	packetizedTCP.AttachPlugin(&fileListTransfer);
#else
	RakNet::RakPeerInterface *rakPeer;
	rakPeer = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor socketDescriptor(localPort,0);
	rakPeer->Startup(1,&socketDescriptor, 1);
	// Plugin will send us downloading progress notifications if a file is split to fit under the MTU 10 or more times
	rakPeer->SetSplitMessageProgressInterval(10);
	rakPeer->AttachPlugin(&autopatcherClient);
	rakPeer->AttachPlugin(&fileListTransfer);
#endif
	printf("started\n");
	char buff[512];
	if (argc<2)
	{
		printf("Enter server IP: ");
		Gets(buff,sizeof(buff));
		if (buff[0]==0)
			//strcpy(buff, "94.198.81.195");
			strcpy(buff, "127.0.0.1");
	}
	else
		strcpy(buff, argv[1]);

#ifdef USE_TCP
	packetizedTCP.Connect(buff,60000,false);
#else
	rakPeer->Connect(buff, 60000, 0, 0);
#endif

	printf("Connecting...\n");
	char appDir[512];
	if (argc<3)
	{
		printf("Enter application directory: ");
		Gets(appDir,sizeof(appDir));
		if (appDir[0]==0)
		{
			strcpy(appDir, "D:/temp2");
		}
	}
	else
		strcpy(appDir, argv[2]);
	char appName[512];
	if (argc<4)
	{
		printf("Enter application name: ");
		Gets(appName,sizeof(appName));
		if (appName[0]==0)
			strcpy(appName, "TestApp");
	}
	else
		strcpy(appName, argv[3]);

	bool patchImmediately=argc>=5 && argv[4][0]=='1';

	if (patchImmediately==false)
		printf("Hit 'q' to quit, 'p' to patch, 'c' to cancel the patch. 'r' to reconnect. 'd' to disconnect.\n");
	else
		printf("Hit 'q' to quit, 'c' to cancel the patch.\n");

	char ch;
	RakNet::Packet *p;
	while (1)
	{
#ifdef USE_TCP
		RakNet::SystemAddress notificationAddress;
		notificationAddress=packetizedTCP.HasCompletedConnectionAttempt();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
		{
			printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
			serverAddress=notificationAddress;
		}
		notificationAddress=packetizedTCP.HasNewIncomingConnection();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_NEW_INCOMING_CONNECTION\n");
		notificationAddress=packetizedTCP.HasLostConnection();
		if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_CONNECTION_LOST\n");


		p=packetizedTCP.Receive();
		while (p)
		{
			if (p->data[0]==ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR)
			{
				char buff[256];
				RakNet::BitStream temp(p->data, p->length, false);
				temp.IgnoreBits(8);
				RakNet::StringCompressor::Instance()->DecodeString(buff, 256, &temp);
				printf("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n");
				printf("%s\n", buff);
			}
			else if (p->data[0]==ID_AUTOPATCHER_FINISHED)
			{
				printf("ID_AUTOPATCHER_FINISHED with server time %f\n", autopatcherClient.GetServerDate());
				double srvDate=autopatcherClient.GetServerDate();
				FILE *fp = fopen("srvDate", "wb");
				fwrite(&srvDate,sizeof(double),1,fp);
				fclose(fp);
			}
			else if (p->data[0]==ID_AUTOPATCHER_RESTART_APPLICATION)
				printf("Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n");

			packetizedTCP.DeallocatePacket(p);
			p=packetizedTCP.Receive();
		}
#else
		p=rakPeer->Receive();
		while (p)
		{
			if (p->data[0]==ID_DISCONNECTION_NOTIFICATION)
				printf("ID_DISCONNECTION_NOTIFICATION\n");
			else if (p->data[0]==ID_CONNECTION_LOST)
				printf("ID_CONNECTION_LOST\n");
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{
				printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				serverAddress=p->systemAddress;
			}
			else if (p->data[0]==ID_CONNECTION_ATTEMPT_FAILED)
				printf("ID_CONNECTION_ATTEMPT_FAILED\n");
			else if (p->data[0]==ID_NO_FREE_INCOMING_CONNECTIONS)
				printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
			else if (p->data[0]==ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR)
			{
				char buff[256];
				RakNet::BitStream temp(p->data, p->length, false);
				temp.IgnoreBits(8);
				RakNet::StringCompressor::Instance()->DecodeString(buff, 256, &temp);
				printf("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n");
				printf("%s\n", buff);
			}
			else if (p->data[0]==ID_AUTOPATCHER_FINISHED)
			{
				printf("ID_AUTOPATCHER_FINISHED with server time %f\n", autopatcherClient.GetServerDate());
				double srvDate=autopatcherClient.GetServerDate();
				FILE *fp = fopen("srvDate", "wb");
				fwrite(&srvDate,sizeof(double),1,fp);
				fclose(fp);
			}
			else if (p->data[0]==ID_AUTOPATCHER_RESTART_APPLICATION)
				printf("Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n");

			rakPeer->DeallocatePacket(p);
			p=rakPeer->Receive();
		}
#endif

		if (kbhit())
			ch=getch();
		else
			ch=0;

		if (ch=='q')
			break;
		else if (ch=='r')
		{
#ifdef USE_TCP
			packetizedTCP.Connect(buff,60000,false);
#else
			rakPeer->Connect(buff, 60000, 0, 0);
#endif
		}
		else if (ch=='d')
		{
#ifdef USE_TCP
			packetizedTCP.CloseConnection(serverAddress);
#else
			rakPeer->CloseConnection(serverAddress, true);
#endif
		}
		else if (ch=='p' || (serverAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS && patchImmediately==true))
		{
			patchImmediately=false;
			char restartFile[512];
			strcpy(restartFile, appDir);
			strcat(restartFile, "/autopatcherRestart.txt");

			double lastUpdateDate;
			FILE *fp = fopen("srvDate", "rb");
			if (fp)
			{
				fread(&lastUpdateDate, sizeof(lastUpdateDate), 1, fp);
				fclose(fp);
			}
			else
				lastUpdateDate=0;

			if (autopatcherClient.PatchApplication(appName, appDir, lastUpdateDate, serverAddress, &transferCallback, restartFile, argv[0]))
			{
				printf("Patching process starting.\n");
			}
			else
			{
				printf("Failed to start patching.\n");
			}
		}
		else if (ch=='c')
		{
			autopatcherClient.Clear();
			printf("Autopatcher cleared.\n");
		}

		RakSleep(30);
	}

	// Dereference so the destructor doesn't crash
	autopatcherClient.SetFileListTransferPlugin(0);

#ifdef USE_TCP
	packetizedTCP.Stop();
#else
	rakPeer->Shutdown(500,0);
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);
#endif
	return 1;
}
Пример #27
0
bool Authenticate(RakNet::Rackspace *rackspaceApi, RakNet::TCPInterface *tcpInterface)
{

	RakNet::SystemAddress serverAddress;
	char authenticationURL[128];
	char rackspaceCloudUsername[128];
	char apiAccessKey[128];

	// See http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf
	// US-based accounts authenticate through auth.api.rackspacecloud.com
	// UK-based accounts authenticate through lon.auth.api.rackspacecloud.com
	printf("Enter authenticationURL: ");
	Gets(authenticationURL, sizeof(authenticationURL));
	if (authenticationURL[0]==0)
	{
		FILE *fp;
		fp = fopen("authenticationURL.txt", "rb");
		if (fp)
		{
			fgets(authenticationURL,128,fp);
			fclose(fp);
			printf("Using %s\n", authenticationURL);
		}
		else
		{
			printf("Can't open authenticationURL.txt");
			return false;
		}
	}

	printf("Enter rackspaceCloudUsername: "******"rackspaceCloudUsername.txt", "rb");
		if (fp)
		{
			fgets(rackspaceCloudUsername,128,fp);
			fclose(fp);
			printf("Using %s\n", rackspaceCloudUsername);
		}
		else
		{
			printf("Can't open rackspaceCloudUsername.txt");
			return false;
		}
	}

	// This is found when you log in, under Your Account, expanded to API Access. Then click Show Key under Enable API Access.
	printf("Enter apiAccessKey: ");
	Gets(apiAccessKey, sizeof(apiAccessKey));
	if (apiAccessKey[0]==0)
	{
		FILE *fp;
		fp = fopen("apiAccessKey.txt", "rb");
		if (fp)
		{
			fgets(apiAccessKey,128,fp);
			fclose(fp);
			printf("Using %s\n", apiAccessKey);
		}
		else
		{
			printf("Can't open apiAccessKey.txt");
			return false;
		}
	}

	serverAddress=rackspaceApi->Authenticate(tcpInterface, authenticationURL, rackspaceCloudUsername, apiAccessKey);
	if (serverAddress==RakNet::UNASSIGNED_SYSTEM_ADDRESS)
		printf("Failed to connect to %s\n", authenticationURL);

	return true;
}
_CONSOLE_2_SetSystemProcessParams
#endif

int main(void)
{
	// Pointers to the interfaces of our server and client.
	// Note we can easily have both in the same program
	RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();
	RakNet::RakNetStatistics *rss;
	server->SetIncomingPassword("Rumpelstiltskin", (int)strlen("Rumpelstiltskin"));
	server->SetTimeoutTime(30000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
//	RakNet::PacketLogger packetLogger;
//	server->AttachPlugin(&packetLogger);

#if LIBCAT_SECURITY==1
	cat::EasyHandshake handshake;
	char public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES];
	char private_key[cat::EasyHandshake::PRIVATE_KEY_BYTES];
	handshake.GenerateServerKey(public_key, private_key);
	server->InitializeSecurity(public_key, private_key, false);
	FILE *fp = fopen("publicKey.dat","wb");
	fwrite(public_key,sizeof(public_key),1,fp);
	fclose(fp);
#endif

	// Holds packets
	RakNet::Packet* p;

	// GetPacketIdentifier returns this
	unsigned char packetIdentifier;

	// Record the first client that connects to us so we can pass it to the ping function
	RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;

	// Holds user data
	char portstring[30];

	printf("This is a sample implementation of a text based chat server.\n");
	printf("Connect to the project 'Chat Example Client'.\n");
	printf("Difficulty: Beginner\n\n");

	// A server
	puts("Enter the server port to listen on");
	Gets(portstring,sizeof(portstring));
	if (portstring[0]==0)
		strcpy(portstring, "1234");
	
	puts("Starting server.");
	// Starting the server is very simple.  2 players allowed.
	// 0 means we don't care about a connectionValidationInteger, and false
	// for low priority threads
	// I am creating two socketDesciptors, to create two sockets. One using IPV6 and the other IPV4
	RakNet::SocketDescriptor socketDescriptors[2];
	socketDescriptors[0].port=atoi(portstring);
	socketDescriptors[0].socketFamily=AF_INET; // Test out IPV4
	socketDescriptors[1].port=atoi(portstring);
	socketDescriptors[1].socketFamily=AF_INET6; // Test out IPV6
	bool b = server->Startup(4, socketDescriptors, 2 )==RakNet::RAKNET_STARTED;
	server->SetMaximumIncomingConnections(4);
	if (!b)
	{
		printf("Failed to start dual IPV4 and IPV6 ports. Trying IPV4 only.\n");

		// Try again, but leave out IPV6
		b = server->Startup(4, socketDescriptors, 1 )==RakNet::RAKNET_STARTED;
		if (!b)
		{
			puts("Server failed to start.  Terminating.");
			exit(1);
		}
	}
	server->SetOccasionalPing(true);
	server->SetUnreliableTimeout(1000);

	DataStructures::List< RakNet::RakNetSocket2* > sockets;
	server->GetSockets(sockets);
	printf("Socket addresses used by RakNet:\n");
	for (unsigned int i=0; i < sockets.Size(); i++)
	{
		printf("%i. %s\n", i+1, sockets[i]->GetBoundAddress().ToString(true));
	}

	printf("\nMy IP addresses:\n");
	for (unsigned int i=0; i < server->GetNumberOfAddresses(); i++)
	{
		RakNet::SystemAddress sa = server->GetInternalID(RakNet::UNASSIGNED_SYSTEM_ADDRESS, i);
		printf("%i. %s (LAN=%i)\n", i+1, sa.ToString(false), sa.IsLANAddress());
	}

	printf("\nMy GUID is %s\n", server->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());
	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.");
	char message[2048];

	// Loop for input
	while (1)
	{

	// This sleep keeps RakNet responsive
	RakSleep(30);

	if (kbhit())
	{
		// Notice what is not here: something to keep our network running.  It's
		// fine to block on gets or anything we want
		// Because the network engine was painstakingly written using threads.
		Gets(message,sizeof(message));

		if (strcmp(message, "quit")==0)
		{
			puts("Quitting.");
			break;
		}

		if (strcmp(message, "stat")==0)
		{
			rss=server->GetStatistics(server->GetSystemAddressFromIndex(0));
			StatisticsToString(rss, message, 2);
			printf("%s", message);
			printf("Ping %i\n", server->GetAveragePing(server->GetSystemAddressFromIndex(0)));
	
			continue;
		}

		if (strcmp(message, "ping")==0)
		{
			server->Ping(clientID);

			continue;
		}

		if (strcmp(message, "pingip")==0)
		{
			printf("Enter IP: ");
			Gets(message,sizeof(message));
			printf("Enter port: ");
			Gets(portstring,sizeof(portstring));
			if (portstring[0]==0)
				strcpy(portstring, "1234");
			server->Ping(message, atoi(portstring), false);

			continue;
		}

		if (strcmp(message, "kick")==0)
		{
			server->CloseConnection(clientID, true, 0);

			continue;
		}

		if (strcmp(message, "getconnectionlist")==0)
		{
			RakNet::SystemAddress systems[10];
			unsigned short numConnections=10;
			server->GetConnectionList((RakNet::SystemAddress*) &systems, &numConnections);
			for (int i=0; i < numConnections; i++)
			{
				printf("%i. %s\n", i+1, systems[i].ToString(true));
			}
			continue;
		}

		if (strcmp(message, "ban")==0)
		{
			printf("Enter IP to ban.  You can use * as a wildcard\n");
			Gets(message,sizeof(message));
			server->AddToBanList(message);
			printf("IP %s added to ban list.\n", message);

			continue;
		}


		// Message now holds what we want to broadcast
		char message2[2048];
		// Append Server: to the message so clients know that it ORIGINATED from the server
		// All messages to all clients come from the server either directly or by being
		// relayed from other clients
		message2[0]=0;
		strcpy(message2, "Server: ");
		strcat(message2, message);
	
		// message2 is the data to send
		// strlen(message2)+1 is to send the null terminator
		// HIGH_PRIORITY doesn't actually matter here because we don't use any other priority
		// RELIABLE_ORDERED means make sure the message arrives in the right order
		// We arbitrarily pick 0 for the ordering stream
		// RakNet::UNASSIGNED_SYSTEM_ADDRESS means don't exclude anyone from the broadcast
		// true means broadcast the message to everyone connected
		server->Send(message2, (const int) strlen(message2)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
	}

		// Get a packet from either the server or the client

		for (p=server->Receive(); p; server->DeallocatePacket(p), p=server->Receive())
		{
			// We got a packet, get the identifier with our handy function
			packetIdentifier = GetPacketIdentifier(p);

			// Check if this is a network message packet
			switch (packetIdentifier)
			{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				printf("ID_DISCONNECTION_NOTIFICATION from %s\n", p->systemAddress.ToString(true));;
				break;


			case ID_NEW_INCOMING_CONNECTION:
				// Somebody connected.  We have their IP now
				printf("ID_NEW_INCOMING_CONNECTION from %s with GUID %s\n", p->systemAddress.ToString(true), p->guid.ToString());
				clientID=p->systemAddress; // Record the player ID of the client

				printf("Remote internal IDs:\n");
				for (int index=0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++)
				{
					RakNet::SystemAddress internalId = server->GetInternalID(p->systemAddress, index);
					if (internalId!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
					{
						printf("%i. %s\n", index+1, internalId.ToString(true));
					}
				}

				break;

			case ID_INCOMPATIBLE_PROTOCOL_VERSION:
				printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
				break;

			case ID_CONNECTED_PING:
			case ID_UNCONNECTED_PING:
				printf("Ping from %s\n", p->systemAddress.ToString(true));
				break;

			case ID_CONNECTION_LOST:
				// Couldn't deliver a reliable packet - i.e. the other system was abnormally
				// terminated
				printf("ID_CONNECTION_LOST from %s\n", p->systemAddress.ToString(true));;
				break;

			default:
				// The server knows the static data of all clients, so we can prefix the message
				// With the name data
				printf("%s\n", p->data);

				// Relay the message.  We prefix the name for other clients.  This demonstrates
				// That messages can be changed on the server before being broadcast
				// Sending is the same as before
				sprintf(message, "%s", p->data);
				server->Send(message, (const int) strlen(message)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->systemAddress, true);

				break;
			}

		}
	}

	server->Shutdown(300);
	// We're done with the network
	RakNet::RakPeerInterface::DestroyInstance(server);

	return 0;
}
int main(void)
{
	char ch;

#ifdef USE_TCP
	RakNet::PacketizedTCP tcp1;
#else
	RakNet::RakPeerInterface *rakPeer;
#endif

	// directoryDeltaTransfer is the main plugin that does the work for this sample.
	RakNet::DirectoryDeltaTransfer directoryDeltaTransfer;
	// The fileListTransfer plugin is used by the DirectoryDeltaTransfer plugin and must also be registered (you could use this yourself too if you wanted, of course).
	RakNet::FileListTransfer fileListTransfer;
	// Read files in parts, rather than the whole file from disk at once
	RakNet::IncrementalReadInterface iri;
	directoryDeltaTransfer.SetDownloadRequestIncrementalReadInterface(&iri, 1000000);

#ifdef USE_TCP
	tcp1.AttachPlugin(&directoryDeltaTransfer);
	tcp1.AttachPlugin(&fileListTransfer);
#else
	rakPeer = RakNet::RakPeerInterface::GetInstance();
	rakPeer->AttachPlugin(&directoryDeltaTransfer);
	rakPeer->AttachPlugin(&fileListTransfer);
	// Get download progress notifications.  Handled by the plugin.
	rakPeer->SetSplitMessageProgressInterval(100);
#endif
	directoryDeltaTransfer.SetFileListTransferPlugin(&fileListTransfer);

	printf("This sample demonstrates the plugin to incrementally transfer compressed\n");
	printf("deltas of directories.  In essence, it's a simple autopatcher.\n");
	printf("Unlike the full autopatcher, it has no dependencies.  It is suitable for\n");
	printf("patching from non-dedicated servers at runtime.\n");
	printf("Difficulty: Intermediate\n\n");

	printf("Enter listen port. Enter for default. If running two instances on the\nsame computer, use 0 for the client.\n");
	unsigned short localPort;
	char str[256];
	Gets(str, sizeof(str));
	if (str[0]==0)
		localPort=60000;
	else
		localPort=atoi(str);
	RakNet::SocketDescriptor socketDescriptor(localPort,0);
#ifdef USE_TCP
	bool b=tcp1.Start(localPort,8);
	RakAssert(b);
#else
	if (rakPeer->Startup(8,&socketDescriptor, 1)!=RakNet::RAKNET_STARTED)
	{
		RakNet::RakPeerInterface::DestroyInstance(rakPeer);
		printf("RakNet initialize failed.  Possibly duplicate port.\n");
		return 1;
	}
	rakPeer->SetMaximumIncomingConnections(8);
#endif

	printf("Commands:\n");
	printf("(S)et application directory.\n");
	printf("(A)dd allowed uploads from subdirectory.\n");
	printf("(D)ownload from subdirectory.\n");
	printf("(C)lear allowed uploads.\n");
	printf("C(o)nnect to another system.\n");
	printf("(Q)uit.\n");

	RakNet::SystemAddress sysAddrZero=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
	RakNet::TimeMS nextStatTime = RakNet::GetTimeMS() + 1000;

	RakNet::Packet *p;
	while (1)
	{
		/*
		if (//directoryDeltaTransfer.GetNumberOfFilesForUpload()>0 &&
			RakNet::GetTimeMS() > nextStatTime)
		{
			// If sending, periodically show connection stats
			char statData[2048];
			RakNetStatistics *statistics = rakPeer->GetStatistics(rakPeer->GetSystemAddressFromIndex(0));
		//	if (statistics->messagesOnResendQueue>0 || statistics->internalOutputQueueSize>0)
			if (rakPeer->GetSystemAddressFromIndex(0)!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			{
				StatisticsToString(statistics, statData, 2);
				printf("%s\n", statData);
			}
			
			nextStatTime=RakNet::GetTimeMS()+5000;
		}
		*/

		// Process packets
#ifdef USE_TCP
		p=tcp1.Receive();
#else
		p=rakPeer->Receive();
#endif

#ifdef USE_TCP
		RakNet::SystemAddress sa;
		sa=tcp1.HasNewIncomingConnection();
		if (sa!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
		{
			printf("ID_NEW_INCOMING_CONNECTION\n");
			sysAddrZero=sa;
		}
		if (tcp1.HasLostConnection()!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_DISCONNECTION_NOTIFICATION\n");
		if (tcp1.HasFailedConnectionAttempt()!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_CONNECTION_ATTEMPT_FAILED\n");
		sa=tcp1.HasCompletedConnectionAttempt();
		if (sa!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
		{
			printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
			sysAddrZero=sa;
		}
#endif

		while (p)
		{

#ifdef USE_TCP
			tcp1.DeallocatePacket(p);
			tcp1.Receive();
#else

			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
			{
				printf("ID_NEW_INCOMING_CONNECTION\n");
				sysAddrZero=p->systemAddress;
			}
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{
				printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				sysAddrZero=p->systemAddress;
			}
			else if (p->data[0]==ID_DISCONNECTION_NOTIFICATION)
				printf("ID_DISCONNECTION_NOTIFICATION\n");
			else if (p->data[0]==ID_CONNECTION_LOST)
				printf("ID_CONNECTION_LOST\n");
			else if (p->data[0]==ID_CONNECTION_ATTEMPT_FAILED)
				printf("ID_CONNECTION_ATTEMPT_FAILED\n");
			rakPeer->DeallocatePacket(p);
			p=rakPeer->Receive();
#endif
		}

		if (kbhit())
		{
			ch=getch();
			if (ch=='s')
			{
				printf("Enter application directory\n");
				Gets(str, sizeof(str));
				if (str[0]==0)
					strcpy(str, "C:/Temp");
				directoryDeltaTransfer.SetApplicationDirectory(str);
				printf("This directory will be prefixed to upload and download subdirectories.\n");
			}
			else if (ch=='a')
			{
				printf("Enter uploads subdirectory\n");
				Gets(str, sizeof(str));
				directoryDeltaTransfer.AddUploadsFromSubdirectory(str);
				printf("%i files for upload.\n", directoryDeltaTransfer.GetNumberOfFilesForUpload());
			}
			else if (ch=='d')
			{
				char subdir[256];
				char outputSubdir[256];
				printf("Enter remote subdirectory to download from.\n");
				printf("This directory may be any uploaded directory, or a subdir therein.\n");
				Gets(subdir,sizeof(subdir));
				printf("Enter subdirectory to output to.\n");
				Gets(outputSubdir,sizeof(outputSubdir));
                
				unsigned short setId;

				setId=directoryDeltaTransfer.DownloadFromSubdirectory(subdir, outputSubdir, true, sysAddrZero, &transferCallback, HIGH_PRIORITY, 0, 0);
				if (setId==(unsigned short)-1)
					printf("Download failed.  Host unreachable.\n");
				else
					printf("Downloading set %i\n", setId);
			}
			else if (ch=='c')
			{
				directoryDeltaTransfer.ClearUploads();
				printf("Uploads cleared.\n");
			}
			else if (ch=='o')
			{
				char host[256];
				printf("Enter host IP: ");
				Gets(host,sizeof(host));
				if (host[0]==0)
					strcpy(host, "127.0.0.1");
				unsigned short remotePort;
				printf("Enter host port: ");
				Gets(str, sizeof(str));
				if (str[0]==0)
					remotePort=60000;
				else
					remotePort=atoi(str);
#ifdef USE_TCP
				tcp1.Connect(host,remotePort,false);
#else
				rakPeer->Connect(host, remotePort, 0, 0);
#endif
				printf("Connecting.\n");
			}
			else if (ch=='q')
			{
				printf("Bye!\n");
#ifdef USE_TCP
				tcp1.Stop();
#else
				rakPeer->Shutdown(1000,0);
#endif
				break;
			}
		}

		// Keeps the threads responsive
		RakSleep(0);
	}

#ifdef USE_TCP
#else
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);
#endif

	return 0;
}
Пример #30
0
EXPORT void prompt_for_gravity(
	INIT_DATA	*init,
	INIT_PHYSICS	*ip)
{
	RECT_GRID	*gr = &Comp_grid(init);
	float		*L, *U;
	char		s[Gets_BUF_SIZE];
	float		**m;
	int		c, len;
	static char	dname[3][2] = {"x", "y", "z"};
	float		*g;
	GRAVITY		*grav_data;
	int		i, dim;

	gravity_data(init) = NULL;
	screen("The following choices are available for a gravitational "
	       "acceleration\n"
	       "\tNo gravity (N or default)\n"
	       "\tConstant gravity (C or Y)\n"
	       "\tTime dependent gravity (T)\n"
	       "\tAstrophysical (central force) gravity (A)\n"
	       "\tGeneralized Astrophysical gravity (G)\n"
	       "\tRadial gravity with constant magnitude (R)\n");
	screen("Enter choice: ");
	(void) Gets(s);

	scalar(&grav_data,sizeof(GRAVITY));
	gravity_data(init) = grav_data;

	dim = gr->dim;
	grav_data->dim = dim;
	switch (s[0])
	{
	case 'N':
	case 'n':
	case '\0':
	    grav_data->type = NO_GRAVITY;
	    return;
	case 'C':
	case 'c':
	case 'Y': /*For historical compatibility of input files*/
	case 'y': /*For historical compatibility of input files*/
	    grav_data->type = CONSTANT_GRAVITY;
	    g = grav_data->g;
	    g[0] = g[1] = g[2] = 0.0;
	    for (i = 0; i < dim; ++i)
	    {
	        screen("\tEnter %s component of gravity (dflt = 0): ",dname[i]);
	        (void) Gets(s);
	        if (s[0] != '\0')
	    	    (void) sscan_float(s,g+i);
	    }
	    return;
	case 'T':
	case 't':
	    screen("Gravity data consists of an array of uni_arrays (time, g)\n");
	    screen("This data can be entered directly or input from a file\n");
	    screen("Enter either a filename or the number of data points\n");
	    screen("Enter filename or integer: ");
	    (void) Gets(s);
	    if (s[0] == '\0')
	    {
	        grav_data->type = NO_GRAVITY;
	        return;
	    }
	    grav_data->type = TIME_DEPENDENT_GRAVITY;
	    /*Was an integer input?*/
	    len = (int) strlen(s);
	    for (i = 0; i < len; ++i)
	    {
		c = s[i];
		if (!isdigit(c))
		    break;
	    }
	    if (i == len)
	    {
		(void) sscanf(s,"%d",&grav_data->num_time_points);
		bi_array(&m,grav_data->num_time_points,dim+1,FLOAT);
		grav_data->g_of_t = m;
		screen("Enter %d data points consisting of a monotonically "
		       "increasing time value\n",grav_data->num_time_points);
		screen("\tfollowed by a %d vector of gravity "
		       "values for that time\n",dim);
		read_gravity_data(stdin,dim,m,grav_data->num_time_points);
	    }
	    else
	    {
	        FILE	*file = fopen(s,"r");
		int	nf;
		float	x;
		if (file == NULL)
		{
		    screen("ERROR in prompt_for_gravity(), can't open %s",s);
		    clean_up(ERROR);
		}
		/*count entries in file*/
		for (nf = 0; ((c = getc(file)) != EOF); ++nf)
		{
		    (void)ungetc(c,file);
		    if (fscan_float(file,&x) != 1)
			break;
		}
		if ((nf%(dim+1)) != 0)
		{
		    screen("ERROR in prompt_for_gravity(), invalid file\n");
		    clean_up(ERROR);
		}
		grav_data->num_time_points = nf/(dim+1);
		rewind(file);
		bi_array(&m,grav_data->num_time_points,dim+1,FLOAT);
		grav_data->g_of_t = m;
		read_gravity_data(file,dim,m,grav_data->num_time_points);
	    }
	    /*Check for monotonicity of time values*/
	    for (i = 1; i < grav_data->num_time_points; ++i)
	    {
		if (m[i][0] <= m[i-1][0])
		{
		    screen("ERROR in prompt_for_gravity(), "
			   "invalid time values\n");
		    clean_up(ERROR);
		}
	    }
	    return;
	case 'A':
	case 'a':
	    grav_data->type = ASTROPHYSICAL_GRAVITY;
	    grav_data->G = 0.0;
	    grav_data->M = 0.0;
	    L = gr->GL;
	    U = gr->GU;
	    for (i = 0; i < dim; ++i)
		grav_data->center[i] = 0.5*(L[i]+U[i]);
	    screen("Enter the coordinates of the gravity center (dflt =");
	    for (i = 0; i < dim; ++i)
		screen(" %g",grav_data->center[i]);
	    screen("): ");
	    (void) Gets(s);
	    if (s[0] != '\0')
	    {
		float	*cen = grav_data->center;
#if defined(float)
		static const char *fmt = "%lf %lf %lf";
#else /* defined(float) */
		static const char *fmt = "%f %f %f";
#endif /* defined(float) */
		if (sscanf(s,fmt,cen,cen+1,cen+2) != dim)
		{
		    screen("ERROR in prompt_for_gravity(), "
			   "invalid coordinate for gravity center\n");
		    clean_up(ERROR);
		}
	    }
	    screen("Enter the gravitational constant (dflt = %g): ",
		   grav_data->G);
	    (void) Gets(s);
	    if (s[0] != '\0')
		sscan_float(s,&grav_data->G);
	    screen("Enter the mass of the gravity center (dflt = %g): ",
		   grav_data->M);
	    (void) Gets(s);
	    if (s[0] != '\0')
		sscan_float(s,&grav_data->M);
	    return;
	case 'R':
	case 'r':
	    grav_data->type = RADIAL_GRAVITY;
	    grav_data->G = 0.0;
	    grav_data->M = 0.0;
	    L = gr->GL;
	    U = gr->GU;
	    for (i = 0; i < dim; ++i)
		grav_data->center[i] = 0.5*(L[i]+U[i]);
	    screen("Enter the coordinates of the gravity center (dflt =");
	    for (i = 0; i < dim; ++i)
		screen(" %g",grav_data->center[i]);
	    screen("): ");
	    (void) Gets(s);
	    if (s[0] != '\0')
	    {
		float	*cen = grav_data->center;
#if defined(float)
		static const char *fmt = "%lf %lf %lf";
#else /* defined(float) */
		static const char *fmt = "%f %f %f";
#endif /* defined(float) */
		if (sscanf(s,fmt,cen,cen+1,cen+2) != dim)
		{
		    screen("ERROR in prompt_for_gravity(), "
			   "invalid coordinate for gravity center\n");
		    clean_up(ERROR);
		}
	    }
	    screen("Enter the magnitude of the gravitational acceleration "
		   "(dflt = %g): ",grav_data->G);
	    (void) Gets(s);
	    if (s[0] != '\0')
		sscan_float(s,&grav_data->G);
	    return;
	case 'G':
	case 'g':
	    grav_data->type = GENERALIZED_ASTROPHYSICAL_GRAVITY;
            grav_data->roots = &ip->root;
            grav_data->nroots = 1;
	    grav_data->G = 0.0;
	    grav_data->M = 0.0;
	    grav_data->N = 100;
	    for (i = 0; i < dim; ++i)
		grav_data->center[i] = 0.0;
	    screen("Enter the coordinates of the gravity center (dflt =");
	    for (i = 0; i < dim; ++i)
		screen(" %g",grav_data->center[i]);
	    screen("): ");
	    (void) Gets(s);
	    if (s[0] != '\0')
	    {
		float	*cen = grav_data->center;
#if defined(float)
		static const char *fmt = "%lf %lf %lf";
#else /* defined(float) */
		static const char *fmt = "%f %f %f";
#endif /* defined(float) */
		if (sscanf(s,fmt,cen,cen+1,cen+2) != dim)
		{
		    screen("ERROR in prompt_for_gravity(), "
			   "invalid coordinate for gravity center\n");
		    clean_up(ERROR);
		}
	    }
	    screen("Enter the gravitational constant (dflt = %g): ",
		   grav_data->G);
	    (void) Gets(s);
	    if (s[0] != '\0')
		sscan_float(s,&grav_data->G);

            for(i = 0; i < dim; ++i)
            {
                grav_data->GL[i] = gr->GL[i];
                grav_data->GU[i] = gr->GU[i];
                grav_data->gmax[i] = gr->gmax[i];
            }

	    screen("Enter the number of rings the whole domain"
		   "should be divided into (dflt = %d): ", grav_data->N);
	    (void) Gets(s);
	    if (s[0] != '\0')
	    	(void) sscanf(s,"%d",&grav_data->N);
	    //grav_data->Mp = (float*)malloc(grav_data->N*sizeof(float));
	    return;
	default:
	    screen("ERROR in prompt_for_gravity(), "
		   "invalid choice %s\n",s);
	    clean_up(ERROR);
	}
}		/*end prompt_for_gravity*/