python做socket服务端,php做客户端
python server:
#-*-coding=utf-8-*-
from socket import *
#''代表服务器为localhost
myHost = '127.0.0.1'
#在一个非保留端口号上进行监听
myPort = 2011
#设置一个TCP socket对象
sockobj = socket(AF_INET, SOCK_STREAM)
#绑定它至端口号
sockobj.bind((myHost, myPort))
#监听,允许5个连结
sockobj.listen(5)
#直到进程结束时才结束循环
while True:
#等待下一个客户端连结
connection, address = sockobj.accept( )
#连结是一个新的socket
print 'Server connected by', address
data = connection.recv(1024)
if not data: break
print data
connection.send('welcome to server'+data)
connection.close()
'''
while True:
#读取客户端套接字的下一行
data = connection.recv(1024)
#如果没有数量的话,那么跳出循环
if not data: break
#发送一个回复至客户端
#print data
connection.send('welcome to server'+data)
#当socket关闭时eof
connection.close()
'''
php client:
<?php
//确保在连接客户端时不会超时
set_time_limit (0 );
//设置IP和端口号
$address = '127.0.0.1' ;
$port = 2011 ; //调试的时候,可以多换端口来测试程序!
//创建一个SOCKET
if (($sock = socket_create (AF_INET , SOCK_STREAM , SOL_TCP ))< 0 )
{
echo "socket_create() 失败的原因是:" . socket_strerror ($sock ). "<br>" ;
}
//绑定到socket端口
if (($ret = socket_bind ($sock , $address , $port ))< 0 )
{
echo "socket_bind() 失败的原因是:" . socket_strerror ($ret ). "<br>" ;
}
//开始监听
if (($ret = socket_listen ($sock , 4 ))< 0 )
{
echo "socket_listen() 失败的原因是:" . socket_strerror ($ret ). "<br>" ;
}
do {
if (($msgsock = socket_accept ($sock )) < 0 )
{
echo "socket_accept() failed: reason: " . socket_strerror ($msgsock ) . " \n " ;
break ;
}
//发到客户端
$msg = "<font color=red>欢迎进入服务器!</font><br>" ;
socket_write ($msgsock , $msg , strlen ($msg ));
echo "读取客户端发来的信息<br>" ;
$buf = socket_read ($msgsock , 8192 );
$talkback = "收到的信息: $buf <br>" ;
echo $talkback ;
/* if(socket_write($msgsock, $talkback, strlen($talkback))<0)
{
echo "socket_write() failed: reason: " . socket_strerror($msgsock) . "\n";
}
else
{
echo "发送成功";
}*/
//echo $buf;
socket_close ($msgsock );
} while (true );
socket_close ($sock );
?>