stef686 — 2011-03-21T10:04:11-04:00 — #1
I am currently working on a project that requires me to connect to a server and send messages between my site and the server.
Visitor comes to my site, site sends message to server saying "new visitor"
Server sends back "welcome"
My site displays "welcome" on the page - the message sent back by the server
To do this I have found the following code and expected it to work, unfortunately I am getting an error.
error_reporting(E_ALL | E_NOTICE | E_STRICT);
// set some variables
$host = ""; // server IP goes here
$port = 1234; // port thats listening goes here
// don't timeout!
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $host, $port) or die('Could not bind to address '.socket_last_error());
// Start listening for connections
// Accept incoming connections
$client = socket_accept($sock);
// Send message to user
$message = "This is a test message";
// Read user input and loop until
// it says 'quit'
$messageback = socket_read($client, 1024);
// Close the client (child) socket
// Close the master sockets
This produces the following error:
Warning: socket_bind() [function.socket-bind]: unable to bind address : Cannot assign requested address in /home/sites/domain.com/public_html/index.php on line 35
Could not bind to address 99
I've been doing some tests to try and narrow down the problem. The server is running fine and accepting connections, and doesn't care if more than one connection at a time comes through. I can telnet into the server, both from my PC and also via SSH where the site is hosted.
So this suggests that there's nothing other than the PHP code that's causing an issue. There might be something blindingly obvious that I've not done but the socket functions in PHP are one of the few things I've never used before.
Hopefully someone can help!
styloa — 2011-03-22T10:53:23-04:00 — #2
Are you trying to bind the socket to a local IP address?
I assume that what you have is two servers -
server A - hosts your website, it will conect to server B as needed
server B - generates text responses for your visitors, it listens for requests from server A and responds asap.
The code snipet you sent was for server B?
stef686 — 2011-03-23T07:13:39-04:00 — #3
Yes that's correct it's 2 separate servers as you said, the code snippet is hosted on Server A and trying to send messages to Server B
styloa — 2011-03-23T08:02:40-04:00 — #4
I have never used sockets in php, but have wused them in C before... what I think you need to have:
s = socket()
s = socket()
bind(s, local_ip_address, most likely the same as serverB_address above)
in a loop:
(optional) select( ); // wait for a rd event on s
s2 = accept(s)
Does that make sense?