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>
Related
I have an HL7 machine that sends data via TCP on a specified port. I want to continuously listen on that port and display any data received on the screen.
I have this which creates a connection but in my scenario, connection is created by the HL7 machine which then starts sending.
// host and port to connect to
$host = "localhost";
$port = 9876;
// connect to the port
$fp = fsockopen($host, $port, $errno, $errstr);
set_time_limit(0);
// if connection not successfull, display error
if (!$fp)
{
die("Error: Could not open socket for connection!");
}
else
{
// connection successfull, listen for data (1024 bytes by default)
$got = fgets($fp);
// display the data
echo $got;
}
fclose($fp);
You should wait (block) for a socket connection from the HL7 machine. When a connection is received you should process the data then wait for another connection.
If several connections are made at once and your processing of the HL7 message takes a bit of time, it may be wise to process the message/data from the socket in a new thread.
<?php
$condition = true;
$socket = socket_create_listen(port);
socket_set_block($socket);
while (condition) {
socket_accept($socket);
// read data from socket
// condition to break from listening
}
?>
Reference: http://php.net/manual/en/function.socket-set-block.php
I've been trying to connect to a Twitch chat via IRC. I've added an echo function to test where I had connected or not as that page was blank and an account didn't join the IRC.
Here is my code:
<?php
set_time_limit(0);
ini_set('display_errors', 'on');
$datatwitch= array(
'server' => 'irc.twitch.tv',
'port' => 6667,
'nick' => 'greatbritishbgbot',
'name' => 'greatbritishbgbot',
'pass' => 'oauth:HERE',
);
?>
<?php
//The server host is the IP or DNS of the IRC server.
$server_host = $datatwitch['server'];
//Server Port, this is the port that the irc server is running on. Deafult: 6667
$server_port = $datatwitch['port'];
//Server Chanel, After connecting to the IRC server this is the channel it will join.
$server_chan = "#greatbritishbg";
//login password
$nickname = $datatwitch['name'];
$nickname_pass = $datatwitch['pass'];
//Ok, We have a nickname, now lets connect.
$server = array(); //we will use an array to store all the server data.
//Open the socket connection to the IRC server
$server['SOCKET'] = #fsockopen($server_host, $server_port, $errno, $errstr, 2);
if($server['SOCKET'])
{
//Ok, we have connected to the server, now we have to send the login commands.
echo "connected";
SendCommand("PASS $nickname_pass \n\r"); //Sends the password not needed for most servers
SendCommand("NICK $nickname\n\r"); //sends the nickname
SendCommand("USER $nickname USING PHP IRC\n\r"); //sends the user must have 4 paramters
while(!feof($server['SOCKET'])) //while we are connected to the server
{
$server['READ_BUFFER'] = fgets($server['SOCKET'], 1024); //get a line of data from the server
echo "[RECIVE] ".$server['READ_BUFFER']."<br>\n\r"; //display the recived data from the server
/*
IRC Sends a "PING" command to the client which must be anwsered with a "PONG"
Or the client gets Disconnected
*/
//Now lets check to see if we have joined the server
if(strpos($server['READ_BUFFER'], "422")) //422 is the message number of the MOTD for the server (The last thing displayed after a successful connection)
{
//If we have joined the server
SendCommand("JOIN $server_chan\n\r"); //Join the chanel
}
if(substr($server['READ_BUFFER'], 0, 6) == "PING :") //If the server has sent the ping command
{
SendCommand("PONG :".substr($server['READ_BUFFER'], 6)."\n\r"); //Reply with pong
//As you can see i dont have it reply with just "PONG"
//It sends PONG and the data recived after the "PING" text on that recived line
//Reason being is some irc servers have a "No Spoof" feature that sends a key after the PING
//Command that must be replied with PONG and the same key sent.
}
flush(); //This flushes the output buffer forcing the text in the while loop to be displayed "On demand"
}
} else {
echo "connection failed";
}
function SendCommand ($cmd)
{
global $server; //Extends our $server array to this function
#fwrite($server['SOCKET'], $cmd, strlen($cmd)); //sends the command to the server
echo "[SEND] $cmd <br>"; //displays it on the screen
}
?>
It appears I can't Get passed if($server['SOCKET']). Is there anyway I can diagnose this? As I have directly connect with the details in hexChat.
The server had actually been preventing me to use fsocket. After contacting my host and moving away from a shared host it started to work.
Please take a look at this answer: https://stackoverflow.com/a/24835967/1163786
Especially:
$socket = fsockopen($bot["Host"], $bot["Port"], $error1, $error2);
if(!$socket) {
echo 'Crap! fsockopen failed. Details: ' . $error1 . ': ' . $error2;
}
To get the details about the socket error = reason for socket not connecting.
Currently, you have $errno, $errstr on fsockopen, but echo only "connection failed".
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);
}
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.
So I've been able to use AJAX to repeatedly refresh a div on my website, using the following code:
var $container = $("#content");
var refreshId = setInterval(function()
{
$container.load('toad.php').fadeOut("slow").load('response.php').fadeIn("slow"); ;
}, 2000);
This works fine, toad.php gets executed every 2 seconds and the contents update.
toad.php contains the following code currently:
<?php
if ( !($sock = socket_create(AF_INET, SOCK_STREAM, 0)) ) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if (!socket_connect($sock, '127.0.0.1', 45000)) {
//$errorcode = socket_last_error();
//$errormsg = socket_strerror($errorcode);
echo "No sensor available to connect to.\n";
//die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
//Now receive reply from server
if (false !== ($bytes = socket_recv($sock, $buf, 1200, MSG_WAITALL))) {
echo "Read $bytes bytes from socket_recv(). Closing socket...";
}
else {
echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
socket_close($sock);
echo $buf . "\n";
echo "OK.\n";
?>
The issue with this is that the socket is created and connected to every single time the div is refreshed.
If I don't have the socket_create and socket_connect functions in toad.php then the socket_recv function doesn't know about the socket and doesn't work.
My question is how can I get the socket receive code to loop and update the contents of the div without having to re create and connect to the socket every time?
Thanks!
If you can rewrite the server your connecting to to use websocket, you could just connect directly from the browser using socket.io.
http://socket.io/
As others have said, maintaining a persistent PHP connection can be tricky, but if running a NodeJS (or similar) script to handle client connections isn't possible you could serve the websockets from that same PHP script.
Try this approach:
http://devzone.zend.com/209/writing-socket-servers-in-php/
Your toad.php script would run on the command line, listening to your existing socket server, then serving the data to it's own socket server which the browser connects to directly with websocket.