Jump to content

socket programing


Mahdi

Recommended Posts

in the name of Godhello guysI want to create a socket program using php, but at the first it has following error : socket_bind() [function_socket-bind]: Host lookup failed [0]: The requested name is valid, but no data of the requested type was found. in line 19. Could not bind to address. And my source is: <?php // Set time limit to indefinite execution set_time_limit (0); // Set the ip and port we will listen on $address = ' 192.168.0.1'; $port = 8080; // Create a TCP Stream socket $sock = socket_create(AF_INET, SOCK_STREAM, 0); // Bind the socket to an address/port socket_bind($sock, $address, $port) or die('Could not bind to address'); // Start listening for connections socket_listen($sock); /* Accept incoming requests and handle them as child processes */ $client = socket_accept($sock); // Read the input from the client – 1024 bytes $input = socket_read($client, 1024); // Strip all white spaces from input $output = ereg_replace("[ \t\n\r]","",$input).chr(0); // Display output back to client socket_write($client, $output); // Close the client (child) socket socket_close($client); // Close the master sockets socket_close($sock); ?> Above code is my server side program source Please tell me about the error. what does it mean?

Link to comment
Share on other sites

In the name of Mr. Herriman.Hi. Do you really need the socket functions? For plain ol' TCP and UDP sockets, you're better off using stream_socket_client() and stream_socket_server(). They are much more intuitive.You should also keep in mind that there are some things to watch out when you deal with sockets... namely the fact that sends and receives might be partial. You can see in my signature a small library I've made that abstracts those things away, so that you can just say "get me N bytes" and know for certain that you're getting N bytes.

Link to comment
Share on other sites

The source for... my library? The link is in my signature, but if you insist, here:http://pear2.github.com/Net_Transmitter/The download link, as well as docs, are right at that page.

Link to comment
Share on other sites

PHP isn't exactly suitable for creating socket servers (yet)...It doesn't have any threads or stuff like that, so it can't handle the multiple incoming connections that a chat would require.It does support forks using pcntl_fork(), but that extension is only available on UNIX systems. If you have some UNIX to test on (e.g. a host that happens to have the PCNTL extension available), you could do the server there.The way you work with TCP sockets is pretty much the way you work with files:1. If you're making a client, you specify a server to connect to, and at any time, you can either "read" (receive...) or "write" (send...) arbitrary data. The main difference with files is that the data you receive/read is independent from the data you send/write.2. If you're making a server, you specify an IP:port combo you want to receive client connections on, and then every time you're ready to handle a new incoming connection, you open a new stream where you (again) either "receive" (read) data from the client, or "send" ("write") data to it.The second thing is where PHP's problem is - you can't accept a new incoming connection while also dealing with another client. You have to, at some point, stop dealing with one client to deal with the next, and yet not forget to go back to the original client. When you don't have threads/forks, doing so is extremely inefficient.

Link to comment
Share on other sites

How does a chat with one client look like? I mean, isn't a chat, by definition, a dialogue (i.e. between two parties)? Or do you want the server to respond with some predefined phrases?Assuming you want that... using my library, here's a very trivial server that first expects messages that are made up of 4 bytes, and responds with 2 byte messages. Connection is closed on a 'DONE' message, and server is terminated with a 'KILL' message:

<?phpnamespace PEAR2\Net\Transmitter;require_once 'PEAR2/Net/Transmitter/Autoload.php';$server = stream_socket_server('tcp://127.0.0.1:6666');while (true) {    try {        $conn = new TcpServerConnection($server, -1);        while ('DONE' !== $message = $conn->receive(4)) {            switch ($message) {                case '######':                    $conn->send('no');                    break;                case 'OPPS':                    $conn->send('oh');                    break;                case 'HERE':                    $conn->send('ty');                    break;                case 'KILL':                    break 3;                default:                    $conn->send('??');            }        }    } catch (Exception $e) {        echo $e;    }}

And here's a client that sends a few messages to that server, and echoes the responses:

<?phpnamespace PEAR2\Net\Transmitter;require_once 'PEAR2/Net/Transmitter/Autoload.php';$c = new TcpClient('127.0.0.1', 6666);$c->send('######');echo $c->receive(2), "\n";$c->send('OPPS');echo $c->receive(2), "\n";$c->send('######');echo $c->receive(2), "\n";$c->send('DONE');

NOTE: To successfully run this, the server must be executed from the command line, and after that, the client must be executed either from another command line window or from a browser.

Link to comment
Share on other sites

Thanks a lot boen but it has following error in both of them: Fatal error: Namespace declaration statement has to be the very first statement in the script in D:\Program Filess\xampp 1.7.4\htdocs\socket\aa.php on line 2 what does it mean?

Link to comment
Share on other sites

you cant have any code (except 'declare') before namespace declaration. are you trying boen's code or did you modified it?

Edited by birbal
Link to comment
Share on other sites

Remove any whitespace or any other code you may have before the "<?php"... do so in both files.Also, if you're using Notepad, save the file with ANSI encoding. If you're using another editor, save it as UTF-8 without BOM (Notepad can only save as UTF-8 with BOM).

Link to comment
Share on other sites

Remove any whitespace or any other code you may have before the "<?php"... do so in both files. Also, if you're using Notepad, save the file with ANSI encoding. If you're using another editor, save it as UTF-8 without BOM (Notepad can only save as UTF-8 with BOM).
I did what you said and the error was changed like this Warning: require_once(PEAR2/Net/Transmitter/Autoload.php) [function.require-once]: failed to open stream: No such file or directory in D:\Program Filess\xampp 1.7.4\htdocs\socket\aa.php on line 2Fatal error: require_once() [function.require]: Failed opening required 'PEAR2/Net/Transmitter/Autoload.php' (include_path='.;D:\Program Filess\xampp 1.7.4\php\PEAR') in D:\Program Filess\xampp 1.7.4\htdocs\socket\aa.php on line 2 Edited by Mahdi
Link to comment
Share on other sites

Did you actually downloaded the library? Where is it? Judging by the error message, the Autoload.php file (and the rest of the library files, mind you!) must be at either

D:\Program Filess\xampp 1.7.4\php\PEAR\PEAR2\Net\Transmitter\Autoload.php

or

D:\Program Filess\xampp 1.7.4\htdocs\socket\PEAR2\Net\Transmitter\Autoload.php

Where have you put the contents (the contents of the "src" folder that is) instead?

Link to comment
Share on other sites

You are running the server from the command line, right? It shouldn't be started from a browser.You must enable php.exe in your firewall to run any server. Even better, you should add the port "6666" to explicitly allow this particular server. The point is that the firewall slows things down.(The IP is definitely not the problem though; that's the "localhost" IP, so there's nothing faster than that)

Link to comment
Share on other sites

oh server side gives following response ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? and client gives following error Fatal error: Maximum execution time of 30 seconds exceeded in D:\Program Filess\xampp 1.7.4\htdocs\socket\PEAR2\Net\Transmitter\Stream.php on line 303 what does it mean?

Edited by Mahdi
Link to comment
Share on other sites

It looks as if you've swapped the client and server.Only the client echoes stuff, and it does so after it sends a message.The server should never echo anything, but should remain on until it is explicitly shut down.So try to run things the other way around: First, from the command line (this is VITAL!) run the file that currently gives the execution time error, and then run the file that currently produces the "??"s.

Link to comment
Share on other sites

You must run it from php.exe with the file as argument, like:

"D:\Program Filess\xampp 1.7.4\php\php.exe" -f "D:\Program Filess\xampp 1.7.4\htdocs\socket\bb.php"

Link to comment
Share on other sites

It looks as if you've swapped the client and server. Only the client echoes stuff, and it does so after it sends a message. The server should never echo anything, but should remain on until it is explicitly shut down. So try to run things the other way around: First, from the command line (this is VITAL!) run the file that currently gives the execution time error, and then run the file that currently produces the "??"s.
please describe to me how should I do that?
Link to comment
Share on other sites

please describe to me how should I do that?
I just said that in my last post...
You must run it from php.exe with the file as argument, like:
"D:\Program Filess\xampp 1.7.4\php\php.exe" -f "D:\Program Filess\xampp 1.7.4\htdocs\socket\bb.php"

So... go toStart > (All) Programs > Accessories > Command Promptand in the new window (that's the command line), type in
"D:\Program Filess\xampp 1.7.4\php\php.exe" -f "D:\Program Filess\xampp 1.7.4\htdocs\socket\bb.php"

and press Enter.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...