PHP how to connect with sockets and read the response? - php

The title explains it all...
How can i connect to an IP using tcp protocol and read/get the response?
I have searched a lot but i didnt find any solution.
$socket = stream_socket_server("tcp://127.0.0.1:22", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
echo fread($conn, 26);
fclose($conn);
}
fclose($socket);
}
is this code ok?
Does the job?
Because it seems it doesn't do the job...
Thanks in advance

As suggested by others; avoid using port 22. I recommend using an obscure (unused) socket port number > 1024 such as 4444. Anything below 1024 normally requires root access.
If you need to test connectivity for 22 have your server script run additional functions.
As for sending a response back to the connected client use stream_socket_recvfrom($socket, $length, 0, $peer) instead of fread()
Then on the client side add a response listener:
client.php
$socket = stream_socket_client('tcp://127.0.0.1:4444');
if ($socket) {
$sent = stream_socket_sendto($socket, 'message');
if ($sent > 0) {
$server_response = fread($socket, 4096);
echo $server_response;
}
} else {
echo 'Unable to connect to server';
}
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
server.php
$conn = stream_socket_server('tcp://127.0.0.1:4444');
while ($socket = stream_socket_accept($conn)) {
$pkt = stream_socket_recvfrom($socket, 1500, 0, $peer);
if (false === empty($pkt)) {
stream_socket_sendto($socket, 'Received pkt ' . $pkt, 0, $peer);
}
fclose($socket);
usleep(10000); //100ms delay
}
stream_socket_shutdown($conn, \STREAM_SHUT_RDWR);
Run server.php which will listen in an endless loop listening for a non-empty packet
once server.php receives a packet it will respond back to the connected client with the received packet.
Then execute client.php which will send 'message' to server.php
Once sent it will then retrieve and echo the response from server.php which should read 'Received pkt message'

From http://php.net/stream_socket_accept
Accept a connection on a socket previously created by stream_socket_server().
That means it waits that one client wants to connect. (You just bind yourself to the port, but don't connect anything)
And fread is also the wrong function to use with socket_* functions. Correct function would be stream_socket_recvfrom().
But this really isn't what you seem to want. You appearently want to open a connection to some place. So fsockopen() is the right function:
$conn = fsockopen("127.0.0.1", 22, $errno, $errstr);
if (!$conn) {
echo "$errstr ($errno)<br />\n";
} else {
echo fread($conn, 26);
fclose($socket);
}

Related

Unable send message continuity via socket

I'm trying to make a communication system between python server and php client. Php client will connect to python server and send a message and close to make completely. But when I connect and send message again, python server can't receive this message while in opening then client can't get you are client111111111111111111111111111111111111111111 line, but when I telnet on commandline to connect to server then everything work well. Please help! Sorry my bad english.
Here is my code.
python server
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall('you are client111111111111111111111111111111111111111111')
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
php client
socket.php
<?php
$fp = fsockopen("127.0.0.1", 10000, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "You message");
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
Update question : Message sent via ajax when press a button event
<script type="text/javascript">
function buttonPress() {
$.ajax({
type : 'post',
url : 'socket.php',
success : function(mess){
}
});
}
</script>

PHP: TCP sockets, 'unable to bind address'

i've seen other people with this problem, but maybe i can explain my situation and you can point out where the issue might be.
im getting a 'Warning : socket_bind(): unable to bind address [98]: Address already in use' error.
the situation is this. I am using a web application to trigger another program to perform tasks (from a webpage interface). The results of that program are sent through a socket to my web application that is listening on a socket.
first i create and open the socket, then i trigger the other program, then when that program is finished it should send its results back through the socket.
it works fine the first try. Then the next try (i trigger this process many times) i get the above socket bind error when trying to open the socket, obviously the socket is still bound.
i wait about a minute and i can successfully run the process again. I think the socket connection timesout.
I dont know if the problem is because of the way i have structure my socket code, or if the problem is in the external program that i am triggering. I dont know much about the internals of the external program as its a jar file built by someone else.
heres the code i use for creating and handling the socket. I just used an example on php.net and altered it for my needs.
$port1 = 15000;
// configure the socket
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port2 = 54321;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$error = 'none';
if ($sock) {
if (socket_bind($sock, $address, $port2)) {
if (socket_listen($sock, 5)) {
// trigger external process
if (start_calibration()) {
$buf = array();
// listen to the socket for incoming messages
do {
// if incomming connection is not accepted break out and close socket
if (($msgsock = socket_accept($sock)) === false) {
break;
}
do {
// if cant read socket then break out and close socket
if (false === ($buf = socket_read($msgsock, 2048, PHP_BINARY_READ))) {
break 2;
}
$buf = unpack('C*', $buf);
socket_close($msgsock);
break 2;
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
// code to handle data recieved through the socket
}
else {
// start_calibration failed
$error = 'start_calibration failed';
socket_close($sock);
}
}
else {
// socket_listen failed
$error = 'socket_listen failed';
socket_close($sock);
}
}
else {
// socket_bind failed
$error = 'socket_bind failed';
socket_close($sock);
}
}
else {
// socket_create failed
$error = 'socket_create failed';
}
$data['error'] = $error;
echo json_encode($data);
also, is there is a more efficient way to handle the closing of sockets if there is problems with lines like 'socket_bind', 'socket_listen' etc?
Did you try to set the flag SO_REUSEADDR on your socket?
There's a sample in the socket_set_option's documentation.

Socket_read() says "not a valid resource"

I am learning socket programming and experimenting using php.
I wanted to connect to a socket-server using a client and read the response of the server from the client.
Codes for :
Server.php:
$address="127.0.0.1";
$port=3343;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
socket_write($client, "Welcome!!", 1024);
socket_close($socket);
Client.php
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo socket_read($sk, 256);
//echo "Connected";
}
On connecting,
Server output :
I am here
Client Output :
Warning: socket_read(): supplied resource is not a valid Socket resource in C:\xampp\htdocs\users\srv\test\client.php on line 16
Found the problem here.
socket_read() doesn't work with sockets which have not been created with socket_create().
Working code :
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
while (!feof($sk)) echo fgets($sk, 256); //This does the trick
//echo "Connected";
}
You are mixing the resource types.
fsockopen returns a file pointer. You need to use fread, fwrite etc. on it, and not socket_read.
socket_read accepts socket resources create with socket_create or socket_accept
Example for fsockopen from the PHP manual page:
<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
?>
fsockopen reference
socket_read reference

Query if Shoutcast Server is Offline or Online with PHP

I'm trying to use a script to query if a Shoutcast Server is online or offline. The code below is what I'm using at the moment.
$vt_ip = "ip";
$vt_port = "port";
$output = #fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if (!$output) {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
#fclose($output);
But it doesn't update, it is stuck on Offline status.
Any help would be greatly appreciated.
$vt_ip = "ip";
$vt_port = "port";
$conn = fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if(!$conn){
echo $errno;
}else{
fwrite($conn, "\n");
$output = fread($conn, 1024);
fclose($conn);
if ($output == "") {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
}
It isn't enough to simply make a TCP connection to a SHOUTcast server to determine if the stream is working. In fact, a SHOUTcast server that is running will always accept yourTCP connection, even if there is no stream for playback.
You must connect, request the stream, and then check the return status code. Once connected, send this data:
GET /; HTTP/1.0
Follow that by a \r\n\r\n. Now, read data back from the stream until you get the \r\n\r\n. Then, you can disconnect. Check the status code from the first response line and see if it's 200. If it is, you've got an active stream.

socket connection code of php

I am writing a simple php socket code.
Here is my code
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
?>
when I run this program my browser only shows waiting for localhost.
Is there any problem in my code?
I am using xammp 1.7.4 .
Another thing I want to know if I want to get a HTTP or FTP request do I have change only the port number?
I verified the code and tested in my system and it works correctly. Showing as "client is here" after running the client.
File Name: server.php
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
socket_close($socket);
?>
First run the server.php file.
File: client.php
<?php
$host="127.0.0.1" ;
$port=9875;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo "Connected";
}
?>
Now run the client.php
Your output should be like this (as I got in my system)
I am hereclient is here
If not, make sure your firewall is not blocking the request. Temporarily disable antivirus if you have one.
That is the expected behaviour of waiting.
The program you have written is a socket server which is ready to listen to the connection with the specified port, until then it will wait.
You can create a client who connects so that you will see the response "Client is here". The client can be any programming language including PHP.
Below is a sample code in PHP (I didn't verify it).
$fp = stream_socket_client("127.0.0.1:9875", $errno, $errstr);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
// Handle code here for reading/writing
}
You can check this link for sample client code in PHP.
EDIT
$host = "127.0.0.1";
$port = 9875;
$timeout = 30;
$sk = fsockopen($host, $port, $errnum, $errstr, $timeout);
if (!is_resource($sk)) {
exit("connection fail: " . $errnum . " " . $errstr);
} else {
echo "Connected";
}

Categories