之前一直听说socket,也没有研究过。最近在研究golang。简单的研究了一下golang的socket。今天也顺便在网上看看php的socket。总结一个简单的例子。
服务器端的代码:
02 | define( "HOST" , "localhost" ); |
05 | define( "PORT" , "8001" ); |
11 | $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die ( "Could not create socket\n" ); |
14 | socket_bind( $socket , HOST, PORT) or die ( "Could not bind to socket\n" ); |
17 | socket_listen( $socket , 3) or die ( "Could not set up socket listener\n" ); |
21 | print_r( "\n\nWaiting client socket ... \n" ); |
24 | $connection = socket_accept( $socket ); |
27 | socket_write( $connection , "Hello client\n" ); |
30 | $input = socket_read( $connection , 1024) or die ( "Could not read input\n" ); |
36 | socket_close( $connection ); |
客户端地址:
03 | define( "HOST" , "localhost" ); |
06 | define( "PORT" , "8001" ); |
12 | $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die ( "Could not create socket\n" ); |
15 | socket_connect( $socket ,HOST, PORT); |
17 | echo ( "Writing to server socket ...\n" ); |
20 | if (!socket_write( $socket , "Hello server\n" )) { |
21 | echo ( "Write failed \n\n" ); |
25 | $data = socket_read( $socket , PORT); |