This will read the text from a remote txt file and print it to server console and chat. If you have any problems getting it to work with your application let me know.
PHP Code:
#include <amxmodx>
#include <sockets>
#define BUFFER_SIZE 1024
//Random remote text file
//http://www.isotc211.org/2005/xlink/version.txt
new const g_szHost[] = "www.isotc211.org";
new const g_szFile[] = "/2005/xlink/version.txt";
new const g_szDataStart[] = "^r^n^r^n";
new Float:g_fSocketWait[ 33 ];
new g_TimedOut[ 33 ];
public plugin_init()
{
register_plugin( "socket example" , "0.1" , "bugsy" );
register_clcmd( "say /getdata" , "cmd_GetData" );
}
public cmd_GetData( id )
{
new iSocket , iError;
iSocket = socket_open( g_szHost , 80 , SOCKET_TCP , iError );
if( ( iSocket <= 0 ) || iError )
return PLUGIN_HANDLED;
static szPacket[256];
g_TimedOut[ id ] = 0;
formatex( szPacket , 255 , "GET %s HTTP/1.1^r^nHost: %s^r^nConnection: close^r^n^r^n" , g_szFile , g_szHost );
socket_send( iSocket , szPacket , strlen( szPacket ) );
g_fSocketWait[ id ] = get_gametime();
new param[ 2 ];
param[ 0 ] = id;
param[ 1 ] = iSocket;
if( !task_exists( 5511 + id ) )
set_task( 0.1 , "CheckRecv" , 5511 + id , param , 2 , "b" );
return PLUGIN_HANDLED;
}
public CheckRecv( param[ 2 ] )
{
new id = param[ 0 ];
new iSocket = param[ 1 ];
static szData[ BUFFER_SIZE ];
static iPos;
if ( socket_change( iSocket ) )
{
//Append data to our receive buffer
socket_recv( iSocket , szData[ iPos ] , BUFFER_SIZE - iPos );
//I noticed sometimes that socket_change was returning true even though no new data was waiting to be read.
//This will verify if new data is actually received.
if ( strlen ( szData[ iPos ] ) )
{
//Set buffer pos to end of received data so the next time we recv data it will be appended
iPos = strlen( szData );
//Set var to the time at which data last recvd
g_fSocketWait[ id ] = get_gametime();
//Here we are looking where the data starts. After the http header there is
//always a 2 carriage returns.
new iDataPos = strfind( szData , g_szDataStart );
//If datapos was found, we have our data
if ( iDataPos != -1 )
{
server_print( szData[ iDataPos + charsmax( szDataStart ) ] );
client_print( id , print_chat , szData[ iDataPos + charsmax( szDataStart ) ] );
iPos = 0;
CloseSocket( id , iSocket );
}
}
}
//If we do not get any response from the server after 5 seconds then we close socket
if( ( get_gametime() - g_fSocketWait[ id ] ) >= 7.0 )
{
client_print( id , print_chat , "* Server took too long to respond" );
iPos = 0;
CloseSocket( id , iSocket );
}
return PLUGIN_HANDLED;
}
public CloseSocket( id , iSocket )
{
remove_task( 5511 + id );
socket_close( iSocket );
}
__________________