#include #include #if defined WIN32 #include #else #include #include #include #include #include #include #include #include #endif #include #include #include "../SDK/amx/amx.h" #include "../SDK/plugincommon.h" typedef void (*logprintf_t)(char* format, ...); logprintf_t logprintf; void **ppPluginData; extern void *pAMXFunctions; AMX *pAMX; #define MYPORT 3490 #define BACKLOG 10 int OnGetText(char *text) { int idx; cell ret; if (!amx_FindPublic(pAMX, "OnSocketText", &idx)) { cell amx_addr, *phys_addr; amx_PushString(pAMX, &amx_addr, &phys_addr, text, 0, 0); amx_Exec(pAMX, &ret, idx); amx_Release(pAMX, amx_addr); } return 1; } void *socket_srv(void *params) { int sockfd, new_fd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; socklen_t sin_size; int yes=1; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); // my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(&(my_addr.sin_zero), '\0', 8); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) // main accept() loop { sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr)); if (!fork()) // child { #if defined WIN32 closesocket(sockfd); #else close(sockfd); #endif char *buffer = (char*) malloc(100); int numbytes; while((numbytes=recv(new_fd, buffer, 99, 0)) != -1) { buffer[numbytes] = '\0'; if (buffer[0] != 13 && buffer[0] != -1 && buffer[0] != 0) { OnGetText(buffer); /* printf("got text: %s\n",buffer); */ } if (!strcmp("exit\0",buffer)) { printf("Closing socket...\n"); break; } if (buffer[0] == 0) break; } #if defined WIN32 closesocket(new_fd); #else close(new_fd); #endif free(buffer); exit(0); } } return 0; } void sockserv_begin() { pthread_t thread1; int iret1; iret1 = pthread_create( &thread1, NULL, socket_srv, (void*) NULL); printf("Socket Thread started.\n"); } static cell AMX_NATIVE_CALL n_init( AMX* amx, cell* params ) { logprintf( "Initalizing Sockserv..\n" ); sockserv_begin(); pAMX = amx; return 1; } AMX_NATIVE_INFO Natives[ ] = { { "sockserv_init", n_init }, { 0, 0 } }; PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData ) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; pAMX = 0; logprintf( "Plugin socksrv got loaded." ); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload( ) { logprintf( "Plugin socksrv got unloaded." ); } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad( AMX *amx ) { return amx_Register( amx, Natives, -1 ); } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload( AMX *amx ) { return AMX_ERR_NONE; }