PDA

View Full Version : آموزش: شاید شروعی برای برنامه نویسی سوکت با این مثال



desatir7316
سه شنبه 27 تیر 1391, 22:43 عصر
سلام دوستان
یه تکه برنامه دارم که با سوکت نوشته شده و توی این برنامه سورو و کلاینت باهم ارتباط برقرار می کنن
کدش به توضیح جندانی نداره چون همه کامنت کذاری شده
اول سرور رو اجرا کنید بعد کلاینت
هرجاش ابهامی بود در خدمتیم:

بخش سرور:

<?php


// set some variables
$host = "127.0.0.1";
$port = 26009;
// don't timeout!
set_time_limit(0);


// create socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// // bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// // start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
do{
ob_flush();
// ob_implicit_flush(true);
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input."<hr>";
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
socket_close($spawn);

}while($input>10);
// close sockets

socket_close($socket);
?>

بخش کلاینت:

<?php
set_time_limit(0);
while(1){
$host = "127.0.0.1";
$port = 26009;
$message = rand(0,100);
$sql="insert into temp values('".$message."');";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
ob_flush ( );
echo "Reply From Server :".$result."<hr>";
}
?>

این لینک هم بخش سوکت رو خیلی خوب پوشش داده میتونید استفاده کنید:
php.net/... (http://ir.php.net/manual/en/book.sockets.php)

موفق و پیروز باشید