Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
14/06/2015, 04:53 PM
(Última modificación: 21/06/2016, 02:48 AM por Destro .)
Sockets Async 1.3b
Descripción:
A diferencia de los demás modulos, este utiliza sockets asincronicos (non-blocking), eso significa que no hay peligro que el servidor se tilde al esperar una respuesta.
Mejoras:
- Sin bloqueo
(asincronico)
- Identificación de sockets controlada
(los demás modulos al pasar un socket invalido te crashean el servidor...)
- Forwards
(sin tener que estar con un task/think en los plugins)
- Soporte para múltiples clientes TCP
(a cada cliente se le asigna un socket nuevo)
- Soporte para UDP
(sendto y recvfrom)
Include:
Código PHP:
enum SOCKET : {} enum { SOCK_TYPE_UDP = 0 , SOCK_TYPE_TCP , SOCK_TYPE_CHILD // Son los nuevos sockets que se crean al aceptar una conexion TCP } native SOCKET : socket_create ( type , customID ) native socket_lasterror () native socket_getip (const hostname [], ip [], len ) native socket_close ( SOCKET : socket ) native socket_bind ( SOCKET : socket , const local_ip []= "" , local_port ) native socket_get_custom ( SOCKET : socket ) native socket_set_custom ( SOCKET : socket , customID ) // TCP native socket_connect ( SOCKET : socket , const hostname [], port ) native socket_send ( SOCKET : socket , const data [], sendsize = 0 ) native socket_recv ( SOCKET : socket , data [], maxlen ) // UDP native socket_sendto ( SOCKET : socket , const ip [], port , const data [], sendsize = 0 ) native socket_recvfrom ( SOCKET : socket , data [], maxlen , ip [], len , & port ) forward fw_sockConnected ( SOCKET : socket , customID ) forward fw_sockClosed ( SOCKET : socket , customID , error ) forward fw_sockAccepted ( SOCKET : socket , customID , SOCKET : cl_sock , const cl_ip [], cl_port ) forward fw_sockReadable ( SOCKET : socket , customID , type ) forward fw_sockWritable ( SOCKET : socket , customID , type )
ChangeLog:
Código:
1.3b
- Fix bug socket_recvfrom
1.3
- Fix bugs win/linux
- Code optimice
1.2
- Fix bugs linux
1.1b
- Fix bugs win/linux
1.1:
- Fix error en linux Centos
- Fix crash al usar socket_close y hookear fw_sockClosed
- Add socket_lasterror()
- Add socket_getip(...)
1.0:
- Codigo corregido para compilar en linux
1.0Beta:
- Publicación
Github: (desactualizado)
Github / Destro- / amxx / sockets_async
Archivos adjuntos
Descargar AMXX / sockets_aync_test.sma (Tamaño: 6.81 KB / Descargas: 820)
sockets_async.inc (Tamaño: 1.34 KB / Descargas: 655)
source.rar (Tamaño: 47.54 KB / Descargas: 282)
bin.rar (Tamaño: 51.09 KB / Descargas: 509)
Mensajes: 4,247
Temas: 94
Registro en: Mar 2014
Reputación:
58
14/06/2015, 04:58 PM
(Última modificación: 29/04/2017, 06:47 PM por totopizza .)
Gracias por el aporte
Estudia siempre; el tiempo es oro, lo material se puede recuperar pero el tiempo no se puede recuperar.
(02/10/2016, 05:05 PM) meTaLiCroSS escribió: Siempre me gusta ayudar cuando alguien esta interesado realmente en ver que esta programando. (08/08/2019, 05:32 PM) meTaLiCroSS escribió: grax x el dato cr4ck
Mis aportes
PLUGINS MAPAS
Menú LANG
[SF] Sistema de Frags
Say System (Admin Prefix)
Mensajes: 369
Temas: 11
Registro en: Feb 2015
Reputación:
3
SOCK_TYPE_CHILD sos un Mangieri terrible.
Después le pego una miradita.
Pacman rip :'v
Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
14/06/2015, 08:00 PM
(Última modificación: 14/06/2015, 08:07 PM por Destro .)
Subido el modulo para linux (sin probar)
Mensajes: 860
Temas: 16
Registro en: Oct 2013
Reputación:
8
a estas con todas destro , jaja exelenteee sirve sirvee
Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
22/06/2015, 03:23 PM
(Última modificación: 22/06/2015, 03:31 PM por Destro .)
Update 1.1
Me hizo renegar como negro para compilarlo en linux y que no pida versiones de GLIBC modernas
Todo sea por las Selfies en el CS
Mensajes: 1,836
Temas: 66
Registro en: Oct 2013
Che destro, tu modulo me carga todo, pero cuando pongo el plugin con el stock no importa si el plugin esta default la cosa es que me aparece unknown, esta todo bien colocado.
¿Alguna solución?
Mensajes: 229
Temas: 59
Registro en: Jun 2015
Reputación:
0
Hola ¿alguien me puede decir como se instala?
solamente reemplazo el sockets que tengo por este?
Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
21/06/2016, 02:51 AM
(Última modificación: 21/06/2016, 02:52 AM por Destro .)
Actualizado v1.3b (win/linux)
Cita: Corregido un error en la native socket_recvfrom que devolvía siempre 0 como puerto
Mensajes: 3,284
Temas: 41
Registro en: Jan 2014
Reputación:
28
A que se debe este log: ?
Me suele aparecer en los logs..
Código:
[SOCKET] Sockets-A: debug4: error:[0][11]
Mensajes: 1,015
Temas: 42
Registro en: Feb 2016
Reputación:
13
Habria alguna forma de obtener datos de un servidor como en el sockets viejo, para hacer un redirect con este module
Osea obtener jugadores, mapa, max de jugadores, y eso.
Mensajes: 3,284
Temas: 41
Registro en: Jan 2014
Reputación:
28
(24/07/2016, 03:16 PM) Exertency escribió: Habria alguna forma de obtener datos de un servidor como en el sockets viejo, para hacer un redirect con este module
Osea obtener jugadores, mapa, max de jugadores, y eso.
Si, tenés que adaptar ciertas funciones que tiene el redirect original en cuanto a obtener los datos recibidos de los servidores.
https://forums.alliedmods.net/showthread.php?t=29886
Pero antes que nada, tendrías que saber algo básico de sockets y luego poder entender casi perfectamente como funciona el módulo de Destro para poder lograr lo que quieres. Tenés que hacer un plugin y tratar de conectarte con algo y ver como funciona, es prueba y error.
Mensajes: 19
Temas: 1
Registro en: Jan 2016
Reputación:
0
Cómo puedo hacer para enviar una screenshot al servidor web usando sockets? La imagen es muy "pesada" (generalmente alrededor de 30kb) para poder ser almacenada en una variable/string, por lo que me sube la imagen recortada, apenas solo un 10% aproximadamente del archivo.
Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
23/01/2017, 05:09 PM
(Última modificación: 23/01/2017, 05:13 PM por Destro .)
pasa lo que tenes y le doy una mirada
también podes darle una mirada al modulo de
curl
la api curl esta exportada en muchos lenguajes, seguro encontrás muchos ejemplos que podes adaptar
Mensajes: 19
Temas: 1
Registro en: Jan 2016
Reputación:
0
23/01/2017, 06:22 PM
(Última modificación: 23/01/2017, 06:27 PM por pepito13 .)
Tengo esto:
Código PHP:
#include <amxmodx> #include <sockets_async> new const upload_file [] = "A3F0CC91.5_1483514216.jpg" new const upload_host [] = "www.miweb.com" new const upload_script [] = "/upload.php" new const download_savefile [] = "addons/amxmodx/logs/amxx-es.htm" new const download_host [] = "www.amxmodx-es.com" new const download_script [] = "/index.php" new const send_udp_ip [] = "190.0.xxx.xxx" const send_udp_port = 27020 const listen_udp_port = 27015 const listen_tcp_port = 8888 new const log_file [] = "sockets_async.log" enum { SOCKET : SOCK_SEND_UDP , SOCKET : SOCK_LISTEN_UDP , SOCKET : SOCK_LISTEN_TCP , SOCKET : SOCK_UPLOAD , SOCKET : SOCK_DOWNLOAD , SOCK_CLIENT } new const sockets_name [][] = { "SEND_UDP" , "LISTEN_UDP" , "LISTEN_TCP" , "UPLOAD" , "DOWNLOAD" , "CLIENT" } new SOCKET : g_sock [ SOCK_CLIENT ] new g_write_download public plugin_init () { register_plugin ( "Test: Sockets Async" , "1.0" , "Destro" ) set_task ( 4.0 , "create_sokets" ) } public create_sokets () { new result /*=== CREATE ============================================================================*/ g_sock [ SOCK_UPLOAD ] = socket_create ( SOCK_TYPE_TCP , SOCK_UPLOAD ) g_sock [ SOCK_DOWNLOAD ] = socket_create ( SOCK_TYPE_TCP , SOCK_DOWNLOAD ) g_sock [ SOCK_LISTEN_TCP ] = socket_create ( SOCK_TYPE_TCP , SOCK_LISTEN_TCP ) g_sock [ SOCK_LISTEN_UDP ] = socket_create ( SOCK_TYPE_UDP , SOCK_LISTEN_UDP ) g_sock [ SOCK_SEND_UDP ] = socket_create ( SOCK_TYPE_UDP , SOCK_SEND_UDP ) for(new type ; type < SOCK_CLIENT ; type ++) { if(! g_sock [ type ]) { log_to_file ( log_file , "*ERROR [%s]: Failed to create socket" , sockets_name [ type ]) return } } log_to_file ( log_file , "Create the sockets successful." ) /******************************************************************************************/ /*=== CONNECT ===========================================================================*/ result = socket_connect ( g_sock [ SOCK_UPLOAD ], upload_host , 80 ) check_connect_error ( result , SOCK_UPLOAD ) result = socket_connect ( g_sock [ SOCK_DOWNLOAD ], download_host , 80 ) check_connect_error ( result , SOCK_DOWNLOAD ) /******************************************************************************************/ /*=== LISTEN ===========================================================================*/ result = socket_bind ( g_sock [ SOCK_LISTEN_TCP ], "" , listen_tcp_port ) check_listen_error ( result , SOCK_LISTEN_TCP ) result = socket_bind ( g_sock [ SOCK_LISTEN_UDP ], "" , listen_udp_port ) check_listen_error ( result , SOCK_LISTEN_UDP ) /******************************************************************************************/ /*=== UDP SEND ===========================================================================*/ socket_sendto ( g_sock [ SOCK_SEND_UDP ], send_udp_ip , send_udp_port , "ecoooooooooooo" ) } check_connect_error ( result , type ) { if( result > 0 ) return if( result == 0 ) log_to_file ( log_file , "*ERROR [%s]: Failed to connect" , sockets_name [ type ]) else log_to_file ( log_file , "*ERROR [%s]: Invalid Hostname/IP." , sockets_name [ type ]) } check_listen_error ( result , type ) { if( result == 0 ) { log_to_file ( log_file , "*ERROR [%s]: Failed to bind" , sockets_name [ type ]) } } /*=== FORWARS ================================================================================*/ public fw_sockConnected ( SOCKET : socket , customID ) { log_to_file ( log_file , "*[%s]: Connection successful." , sockets_name [ customID ]) switch( customID ) { case SOCK_UPLOAD : { new fp = fopen ( upload_file , "rb" ) if(! fp ) { log_to_file ( log_file , "*ERROR [%s]: Coulds not open upload File [%s]" , sockets_name [ customID ], upload_file ) return } new size = file_size ( upload_file , 0 ); new buff [ 2000 ], data [ 1700 ], packet_size , len len = copy ( data , charsmax ( data ), "--642865735weasdasdwe4285675865^r^nContent-Disposition: form-data; name=^" file ^ "; filename=^" 2_7BE95034.8_1483504390 . jpg ^ "^r^n^r^n" ) len += fread_blocks ( fp , data [ len ], charsmax ( data ) - len - 50 , BLOCK_CHAR ) len += copy ( data [ len ], charsmax ( data ) - len , "^r^n--642865735weasdasdwe4285675865--^r^n" ) packet_size = formatex ( buff , charsmax ( buff ), "POST %s HTTP/1.1^nHost: %s^nContent-Type: multipart/form-data; boundary=642865735weasdasdwe4285675865^r^nContent-Length: %d^r^n^r^n" , upload_script , upload_host , len ) memcpy ( data , len , buff [ packet_size ], charsmax ( buff )) copy ( buff [ packet_size ], charsmax ( buff ) - packet_size , data ) packet_size += len len = socket_send ( socket , buff , packet_size ) //server_print("%s", packet_size) log_to_file ( log_file , "*[%s]: Send Packet: %d/%d" , sockets_name [ customID ], len , packet_size ) log_to_file ( "buff.txt" , "%s" , buff ) } case SOCK_DOWNLOAD : { new data [ 256 ] formatex ( data , charsmax ( data ), "GET %s HTTP/1.1^r^nHost: %s^r^n^r^n" , download_script , download_host ) new len = socket_send ( socket , data ) log_to_file ( log_file , "*[%s]: Send Packet: %d/%d" , sockets_name [ customID ], len , strlen ( data )) g_write_download = fopen ( download_savefile , "wb" ) } } } public fw_sockClosed ( SOCKET : socket , customID , error ) { log_to_file ( log_file , "*[%s]: Connection closed, error num(%d)" , sockets_name [ customID ], error ) if( customID == SOCK_DOWNLOAD ) { fclose ( g_write_download ) } } public fw_sockReadable ( SOCKET : socket , customID , type ) { log_to_file ( log_file , "*[%s]: Ready to read data - type:(%d)" , sockets_name [ customID ], type ) new data [ 2048 ], len if( type == SOCK_TYPE_UDP ) { new ip [ 20 ], port do { len = socket_recvfrom ( socket , data , charsmax ( data ), ip , charsmax ( ip ), port ) if( len <= 0 ) break log_to_file ( log_file , "*[%s]: Recv: size:(%d) - strlen(%d) - packet:[%s]" , sockets_name [ customID ], len , strlen ( data ), data ) } while( len == charsmax ( data )) } else { do { len = socket_recv ( socket , data , charsmax ( data )) if( len <= 0 ) { if( len == - 1 ) log_to_file ( log_file , "*ERROR [%s]: Recv: error" , sockets_name [ customID ]) else { log_to_file ( log_file , "*ERROR [%s]: Recv: No data: Close socket" , sockets_name [ customID ]) socket_close ( socket ) } break } if( customID == SOCK_DOWNLOAD ) { log_to_file ( log_file , "*[%s]: Recv: size:(%d) - strlen(%d)" , sockets_name [ customID ], len , strlen ( data )) fwrite_blocks ( g_write_download , data , len , BLOCK_BYTE ) } else { log_to_file ( log_file , "*[%s]: Recv: size:(%d) - strlen(%d) - packet:[%s]" , sockets_name [ customID ], len , strlen ( data ), data ) } } while( len == charsmax ( data )) } } public fw_sockAccepted ( SOCKET : socket , customID , SOCKET : cl_sock , const cl_ip [], cl_port ) { log_to_file ( log_file , "*[%s]: Accepted: client IP:[%s] - Port:(%d) - newsocket:(%d)" , sockets_name [ customID ], cl_ip , cl_port , cl_sock ) socket_set_custom ( cl_sock , SOCK_CLIENT ) } memcpy (const input [], size , output [], maxsize ) { for(new i ; i < size && i < maxsize ; i ++ ) { output [ i ] = input [ i ] } }
Básicamente lo que hice acá fue tratar de subir una imagen .jpg de una screen que previamente fue tomada. Modificando la línea 130, la extensión de buff y data hace que se suba más o menos contenido de la imagen.
Una vez que solucione esto, ya estaría empezando a unirlo con el sXe Events que posteaste (
https://amxmodx-es.com/Thread-API-sXe-In...vents-1-03 ).
Mensajes: 1,455
Temas: 36
Registro en: Oct 2013
Reputación:
6
23/01/2017, 08:55 PM
(Última modificación: 23/01/2017, 08:59 PM por Destro .)
Código PHP:
new const START_FORMDATA [] = "--642865735weasdasdwe4285675865^r^nContent-Disposition: form-data; name=^" file ^ "; filename=^" temp ^ "^r^n^r^n" new const END_FORMDATA [] = "^r^n--642865735weasdasdwe4285675865--^r^n" new const UPLOAD_HOST [] = "localhost" new const UPLOAD_SCRIPT [] = "/screenshot/upload_screen.php" new SOCKET : g_socket , g_fopen , g_hostip [ 16 ] new g_upFilename [ 64 ], g_upInfo [ 168 ], g_upSendBytes public plugin_init () { socket_getip ( UPLOAD_HOST , g_hostip , 15 ) } public TEST___upload () { formatex ( g_upFilename , charsmax ( g_upFilename ), "fotito/A3F0CC91.5_1483514216.jpg" ) formatex ( g_upInfo , charsmax ( g_upInfo ), "datos=%s" , "datos que se enviaran por la url (metodo GET)" ) g_upSendBytes = 0 set_task ( 10.0 , "task_timeout" , TASK_TIMEOUT ) g_socket = socket_create ( SOCK_TYPE_TCP , 0 ) if( socket_connect ( g_socket , g_hostip , 80 ) <= 0 ) { log_to_file ( log_file , "Error al crear el socket: (%d) (%d)" , g_socket , socket_lasterror ()) finish_upload () } } public task_timeout () { finish_upload () } finish_upload () { if( g_socket ) { new SOCKET : sock = g_socket // Fix Bug fw_sockClosed g_socket = SOCKET : 0 socket_close ( sock ) } if( g_fopen ) { fclose ( g_fopen ) g_fopen = 0 } remove_task ( TASK_TIMEOUT ) set_task ( 1.0 , "check_upload" ) } /*=== FORWARS ================================================================================*/ public fw_sockConnected ( SOCKET : socket , customID ) { if( g_socket != socket ) return g_fopen = fopen ( g_upFilename , "rb" ) if(! g_fopen ) { log_to_file ( log_file , "Error al abrir el archivo: [%s]" , g_upFilename ) finish_upload () return } new buff [ 512 ], data_size , packet_size fseek ( g_fopen , 0 , SEEK_END ) data_size = ftell ( g_fopen ) fseek ( g_fopen , 0 , SEEK_SET ) data_size += ( charsmax ( START_FORMDATA ) + charsmax ( END_FORMDATA )) packet_size = formatex ( buff , charsmax ( buff ), "POST %s?%s HTTP/1.1^nHost: %s^nContent-Type: multipart/form-data; boundary=642865735weasdasdwe4285675865^r^nContent-Length: %d^r^n^r^n" , UPLOAD_SCRIPT , g_upInfo , UPLOAD_HOST , data_size ) add ( buff , charsmax ( buff ), START_FORMDATA ) packet_size += charsmax ( START_FORMDATA ) if( socket_send ( socket , buff , packet_size ) <= 0 ) { log_to_file ( log_file , "Error al iniciar la trasnferencia del archivo: (%d)" , socket_lasterror ()) finish_upload () return } send_file () } send_file () { new buff [ 2048 ], read_size , send_size if( g_fopen ) { fseek ( g_fopen , g_upSendBytes , SEEK_SET ) do { read_size = fread_blocks ( g_fopen , buff , charsmax ( buff ), BLOCK_CHAR ) send_size = socket_send ( g_socket , buff , read_size ) if( send_size == 0 ) return if( send_size == - 1 ) { log_to_file ( log_file , "Error al trasnferir el archivo: (%d)" , socket_lasterror ()) finish_upload () return } g_upSendBytes += send_size } while( read_size == charsmax ( buff )) fclose ( g_fopen ) g_fopen = 0 } send_size = socket_send ( g_socket , END_FORMDATA ) if( send_size == 0 ) return if( send_size == - 1 ) { log_to_file ( log_file , "Error al finalizar la trasnferencia del archivo: (%d)" , socket_lasterror ()) finish_upload () return } } public fw_sockClosed ( SOCKET : socket , customID , error ) { if( g_socket != socket ) return g_socket = SOCKET : 0 log_to_file ( log_file , "sockClosed: (%d) (%d)" , socket_lasterror (), error ) finish_upload () } public fw_sockWritable ( SOCKET : socket , customID , type ) { if( g_socket != socket ) return send_file () }
en resumen es esto lo que usaba para subir las screens, si algún día me dan ganas capaz que lo cambie a cURL
Mensajes: 19
Temas: 1
Registro en: Jan 2016
Reputación:
0
Me funcionó de maravilla, mil gracias!
Mensajes: 713
Temas: 32
Registro en: Jul 2014
Reputación:
19
16/08/2018, 08:47 PM
(Última modificación: 17/08/2018, 12:59 AM por LuKks .)
socket_id y socket_num:
https://amxmodx-es.com/Thread-Desvirtue-...#pid186026
socket_handshake y socket_mask:
https://amxmodx-es.com/Thread-Desvirtue-...#pid186036
edit 2: para usar _handshake -> crypto_socket.inc
https://puu.sh/BeO4e/6cfc55a2c7.inc (tiene el sha1 de Destro pero lo modifiqué y su mismo base64 encode).
Muy útil para cuando quieran manejar websocket, otro día veo si armo el _unmask.
edit 3: data > 4kb = crash?
https://amxmodx-es.com/Thread-Desvirtue-...#pid186096
edit: si en el título pones la versión y fecha, después cuando cambies algo, los enlaces anteriores dejan de funcionar.
Mensajes: 1
Temas: 0
Registro en: Jun 2021
Reputación:
0
hello, if TCP is disconnected, how to reconnect
Mensajes: 1
Temas: 0
Registro en: Feb 2022
Reputación:
0
Just wanna say... Even if this is Spanish forum bc this is the only place where I found this modul!
(This occurred as a UDP Server, Clients were tested from C# and PHP and got the same result just the make sure it's not some language converting differences)
If you pass hex(0x00-0x7f) int(0-127) to the server there's no problem,
but after that it get messy... If I convert it to int I'll get negative numbers as int as just gibberish from hex,
but if I convert it as string it work file and represent the correct char that it responsible for the int in ascii.
example: hex(0xef) - dec(239) - ascii(ï) | array content that will be sent to UDP SOCKET: {0xef, 0xef, 0xef}
as a string - "%s" : print just fine that "ïïï" and it's correct
ERRORS:
as a hex - "0x%06x" / "0x%02x" : print received data[] any index 0-3 is return "0xffffffef"
as an integer - "%i" : print the received data[] any index 0-3 is return "-17" and "0" above
if you try to copy any index 0-3 into a 'new temp[1]' and try to print "0x%02x" will return "0x00"
if you try to copy any index 0-3 into a 'new temp[2]' and try to print "0x%02x" will return "0xffffffef"
if you just use any number below dec(127) hex(7f) then it's work fine...
I don't know if this my stupidity or it's amxxpawn falt or what whatever caused it, but I did programed sockets in C# and I don't remember issues like that... I try to just receive the data and just send it back without any converting, and decoding it did give the expected result, so maybe it's an amxxpawn thing.
I spent like 3 hours with debuging this after I realized that not me fricking it up...
If anyone know a solution for that, our just can point out my mistake I would be thankful!