wassili Posted September 26, 2006 Share Posted September 26, 2006 As a newby to socket programming (at least with PHP) I need some info that I don't seem to be able to find.I want to set up a server (php) application that listens to a specific port waiting for multiple clients to connect.I'm able to connect one client and communication is fine. Alll other clients (from different IP's) keep waiting for answers an don't do anything.How do I set up this socket server on a Windows system that can deal with multiple connections. Client will send data periodically to the server, so IMO the socket cannot be closed ...(?)Here is the server code:[code]#!/usr/local/bin/php -q<?phperror_reporting(E_ALL);include "socketclient.php";/* Allow the script to hang around waiting for connections. */set_time_limit(0);/* Turn on implicit output flushing so we see what we're getting * as it comes in. */ob_implicit_flush();if( $argc==1){ echo "\r\n\r\nusage: php socketserver.php [ip-adress] [portnr]\r\n"; exit;} else{ $address = $argv[1]; ( $argc>2) ? $port = $argv[2] : $port=127;}if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { echo "socket_create() failed: reason: " . socket_strerror($sock) . "\n";}if (($ret = socket_bind($sock, $address, $port)) < 0) { echo "socket_bind() failed: reason: " . socket_strerror($ret) . "\n";}if (($ret = socket_listen($sock, 5)) < 0) { echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";}do { $clientSocket = new SocketClient( $sock ); $clientSocket->listen();} while (true);socket_close($sock);?>[/code]and here is the socketclient code[code]<?php/* Class for socket communication* version 0.1* * */include "protocolparser.php";class SocketClient{ var $socket; var $msgsock; var $buf; function SocketClient( $sock ) { if (($this->msgsock = socket_accept($sock)) < 0) { echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n"; break; } else { $this->socket=$sock; echo "\r\nNew socketClient created.\r\n"; } } function write( $msg ) { socket_write($this->msgsock, $msg, strlen($msg)); } function read( $bufSize, $mode) { $this->buf = socket_read($this->msgsock, $bufSize, $mode); return $this->buf; } function listen() { /* Send instructions. */ $msg = "\nWelcome to the PHP Test Server. \n" . "To quit, type 'quit'. To shut down the server type 'shutdown'.\n"; $this->write($msg); do { if (false == $this->read( 2048, PHP_BINARY_READ) ) { echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n"; break 2; } $proto = new ProtocolParser($this->buf); $talkback= $proto->getInfo(); $this->write($talkback); } while (socket_accept($this->socket)); socket_close($msgsock); }}?>[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.