Esta es una breve introducción de uso de Socket con PHP, dare dos ejemplos sencillos, uno de conexion y otro intercambiando ya información utilizando Socket.
Que es un socket?
Socket designa un concepto abstracto por el cual dos programas (posiblemente situados en computadoras distintas) pueden intercambiar cualquier flujo de datos, generalmente de manera fiable y ordenada.
Un Socket queda definido por una dirección IP, un protocolo de transporte y un número de puerto.
Osea, en pocas palabras, para conectar un proceso X con un proceso Y en otra maquina, el proceso X deberá crear un Socket con la dirección IP del proceso Y. También, como en una maquina, existen mas de un proceso, deberá indicarle en que puerto atiende el proceso Y. Por ejemplo para conectarnos a un FTP utilizamos por defecto el puerto 21, asi cada aplicacion tiene asignado un numero de puerto.
Listo, basta de introduccion y vamos a crear un socket para conectarnos con Google.
<?php
/*
*http://www.php.net/manual/en/ref.sockets.php
*/
$host = "www.google.com";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$puerto = 80;
if (socket_connect($socket, $host, $puerto))
{
echo "\nConexion Exitosa, puerto: " . $puerto;
}
else
{
echo "\nLa conexion TCP no se pudo realizar, puerto: ".$puerto;
}
socket_close($socket);
?>
Obviamente, obtendremos “Conexion Exitosa, puerto: 80″, por que obviamente? por que en el puerto 80 lo utiliza el Protocolo de Transferencia de HiperTexto, la conocida World Wide Web.
Si quieren enteder los parametros de socket_create( int $domain , int $type , int $protocol), visiten el manual de la pagina oficial que esta clarisimo, lo estaba por explicar pero mas claro que esto no hay.
En el ejemplo anterior, realizamos una simple conexión, ahora vamos a mandarle un helo y ver que nos devuelve el servidor Web de Google.
<?php
//http://www.php.net/manual/en/ref.sockets.php
$host = "www.google.com";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$puerto = 80;
$conexion = socket_connect($socket, $host, $puerto);
if($conexion)
{
echo "Conexion Exitosa, puerto: " . $puerto."\n\n";
$buffer = "helo $host\r\n";
$salida = ' ';
socket_write($socket, $buffer);
while ($salida = socket_read($socket, 2048))
{
echo $salida;
}
}
else
{
echo "\nLa conexion TCP no se pudo realizar, puerto: ".$puerto;
}
socket_close($socket);
?>
Y obtenemos esto…
Conexion Exitosa, puerto: 80
HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Content-Length: 1350
Date: Fri, 06 Aug 2010 01:09:40 GMT
Server: GFE/2.0
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>400 Bad Request</title>
<style><!--
body {font-family: arial,sans-serif}
div.nav {margin-top: 1ex}
div.nav A {font-size: 10pt; font-family: arial,sans-serif}
span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
div.nav A,span.big {font-size: 12pt; color: #0000cc}
div.nav A {font-size: 10pt; color: black}
A.l:link {color: #6f6f6f}
A.u:link {color: green}
//--></style>
<script><!--
var rc=400;
//-->
</script>
</head>
<body text=#000000 bgcolor=#ffffff>
<table border=0 cellpadding=2 cellspacing=0 width=100%><tr><td rowspan=3 width=1% nowrap>
<b><font face=times color=#0039b6 size=10>G</font><font face=times color=#c41200 size=10>o</font><font face=times color=#f3c518 size=10>o</font><font face=times color=#0039b6 size=10>g</font><font face=times color=#30a72f size=10>l</font><font face=times color=#c41200 size=10>e</font> </b>
<td> </td></tr>
<tr><td bgcolor="#3366cc"><font face=arial,sans-serif color="#ffffff"><b>Error</b></td></tr>
<tr><td> </td></tr></table>
<blockquote>
<H1>Bad Request</H1>
Your client has issued a malformed or illegal request.
<p>
</blockquote>
<table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor="#3366cc"><img alt="" width=1 height=4></td></tr></table>
</body></html>
Claro, Google no entiende un joraca lo que le estamos mandando, por eso nos da un error 400 Bad Request.
Les dejos unos links para que sigan investigando sobre le tema.
- http://www.php.net/manual/en/book.sockets.php
- http://www.php.net/manual/en/ref.sockets.php
- http://www.devshed.com/c/a/PHP/Socket-Programming-With-PHP/
Salutes…, comentar es agradecer.















[...] Programacion de Socket con PHP http://www.zarpele.com.ar/2010/08/programando-socket-con-php/ por chuecko hace 2 segundos [...]
[...] » noticia original [...]
[...] » noticia original [...]
[...] » noticia original [...]
The mortgage loans suppose to be very useful for guys, which would like to organize their organization. In fact, it’s very easy to receive a college loan.
[...] This post was mentioned on Twitter by Sergio Daniel Lepore, Christian González and Christian González, pablo ar. pablo ar said: Programando Sockets con PHP…: Esta es una breve introducción de uso de Socket con PHP, dare dos ejemplos sencillos… http://bit.ly/albvP2 [...]
El cuerpo humano en HTML y PHP…
He encontrado su entrada interesante lo que he añadido un trackback a él en mi blog
…
nice post. thanks.
[...] Programando Sockets con PHP – 503 Hits [...]
Great article. Waiting for more.
I have noticed of the amount of content material you’ve got on this specific website article and have found this incredibly helpful
Can you message me personally with any ideas about just how you designed this blog site appear this amazing , I would certainly be appreciative.
I wish more individuals would produce sites similar to this of which are really enjoyable to go through. Having just about all the fluff floating about on the internet, its rare to go through a website like this instead.
This is really interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I’ve shared your web site in my social networks!
THANK FOR YOUR POST MAN
Thanks for comment…
Thats a great article!
tengo una pregunta. existe alguna forma de comunicar 2 script corriendo en el servidor por este metodo??? saludos
Gracias x compartir