2011-12-23 1 views
0

я установил сервер для прослушивания входящих запросов через порт 1122 на моем 127.0.0.1 Вот мой код:PHP сокет не работает должным образом

<?php 

// set some variables 
$host = "127.0.0.1"; 
$port = 1122; 


// don't timeout! 
//Since this is a server, it's also a good idea to use the set_time_limit() 
//function to ensure that PHP doesn't time out and die() while waiting for 
//incoming client connections. 

set_time_limit(0); 


// create socket 
// The AF_INET parameter specifies the domain, while the SOCK_STREAM 
// parameter tells the function what type of socket 
// to create (in this case, TCP). 
//If you wanted to create a UDP socket, you could use the 
//following line of code instead:socket_create(AF_INET, SOCK_DGRAM, 0) 

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create 
socket\n"); 


// bind socket to port 
//Once a socket handle has been created, the next step is to attach, 
//or "bind", it to the specified address and port. 
//This is accomplished via the socket_bind() function. 

$result = socket_bind($socket, $host, $port) or die("Could not bind to 
socket\n"); 


// start listening for connections 
//With the socket created and bound to a port, it's time to start listening 
//for incoming connections. PHP allows you to set the socket up as a listener 
//via its socket_listen() function, which also allows you to specify the number 
//of queued connections to allow as a second parameter (here 3) 

$result = socket_listen($socket, 3) or die("Could not set up socket 
listener\n"); 


// accept incoming connections 
// spawn another socket to handle communication 
//Once a client connection is received, the socket_accept() function springs 
//into action, accepting the connection request and spawning another 
//child socket to handle messaging between the client and the server. 
//This child socket will now be used for all subsequent communication 
//between the client and server. 

$spawn = socket_accept($socket) or die("Could not accept incoming 
connection\n"); 

// read client input 
//With a connection established, the server now waits for the client 
//to send it some input - this input is read via the socket_read() function, 
//and assigned to the PHP variable $input. 
//The second parameter to socket_read() specifies the number of bytes of input to read - 
//you can use this to limit the size of the data stream read from the client. 
//Note that the socket_read() function continues to read data from the client 
//until it encounters a carriage return (\n), a tab (\t) or a \0 character. 
//This character as treated as the end-of-input character, and triggers 
//the next line of the PHP script. 

$input = socket_read($spawn, 1024) or die("Could not read input\n"); 

// clean up input string 
//The server now must now process the data sent by the client - in this example, 
//this processing merely involves reversing the input string 
//and sending it back to the client. 
//This is accomplished via the socket_write() function, which makes it possible 
//to send a data stream back to the client via the communication socket. 
//The socket_write() function needs three parameters: a reference to the socket, 
//the string to be written to it, and the number of bytes to be written. 

$input = trim($input); 

// reverse client input and send back 
$output = strrev($input) . "\n"; 
socket_write($spawn, $output, strlen ($output)) or die("Could not write 
output\n"); 


// close sockets 
//Once the output has been sent back to the client, both generated sockets 
//are terminated via the socket_close() function. 

socket_close($spawn); 
socket_close($socket); 
?> 

это будет слушать клиента и возвращать обратную величину ofoutout.

Код не дает ошибок. на самом деле, когда я перехожу к localhost/socket.php, он будет продолжать загрузку.

Теперь я открываю соединение telnet с помощью terraterm, и появляется белая страница. Если я ввожу любое значение или ударяю любую клавишу, соединение будет потеряно.

Любая идея, почему это происходит?

С наилучшими пожеланиями

+0

Что вы ожидаете вместо этого? Кроме того, используйте расширение [Streams] (http://www.php.net/manual/en/book.stream.php) - он более доступен и с ним легко работать. – DaveRandom

+0

Я ожидаю увидеть все, что говорит, что я подключен, и когда я ввожу строку, он инвертирует ее и возвращает ее. – Momo

+1

Может захотеть посмотреть на node.js для создания демона сервера сокетов. Будет намного лучше работать. – dqhendricks

ответ

1

Проблема заключается в том, вероятно, что ваш термин тера использует режим «символ», который означает, что каждый печатаемый символ напрямую отправить на сервер.

Это приводит к немедленному возврату socket_read только одним символом.

Вы можете установить PHP_NORMAL_READ при вызове socket_read:

$input = socket_read($spawn, 1024, PHP_NORMAL_READ) 
    or die("Could not read input\n"); 

Без этого флага socket_read делает не читать, пока \n не написано.

В противном случае он ведет себя нормально. Сценарий не записывает никакого вывода в браузер, поэтому браузер просто ждет, пока не наступит некоторое время ожидания (ваш веб-сервер может завершить PHP-скрипт, потому что ничего не написано).

 Смежные вопросы

  • Нет связанных вопросов^_^