Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to a TCP/IP server via php script [closed]

Tags:

php

tcp

I need to implement a php script on my website that would do the following:

  1. Connect to a remote server
  2. Send packet to the server
  3. Receive packet from the server

Everything is already configurated on the server side to respond to packet requests, I only need to figure out how to use php to connect to TCP/IP server.

Any ideas in which direction to look?

like image 282
John Smith Avatar asked Dec 29 '12 11:12

John Smith


People also ask

What happens when a TCP connection is closed?

The TCP session is sending packets as fast as possible, so when the client sends the FIN and closes its part, the server is still sending lots of data for a moment. In this case, the client sends RST packets until the server stops sending data.

Which side of a TCP connection is allowed to initiate a close?

The figure above also shows how a TCP connection is closed (also called cleared or terminated). Either end can initiate a close operation, and simultaneous closes are also supported but are rare. Traditionally, it was most common for the client to initiate a close.

Can a server close a TCP connection?

Any HTTP client, server, or proxy can close a TCP transport connection at any time.

How do I know if a TCP socket is closed?

You could check if the socket is still connected by trying to write to the file descriptor for each socket. Then if the return value of the write is -1 or if errno = EPIPE, you know that socket has been closed.


1 Answers

Easily with php sockets:

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Your message");
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

To read more, go to http://php.net/manual/en/function.fsockopen.php

like image 178
TheHorse Avatar answered Oct 03 '22 22:10

TheHorse