用python做socket是一件非常爽的事,那么我们就来实现服务器端和客户端(客户端分python版和php版)
首先我们来看服务器端代码:
#coding=gbk
#pythonsocket通信
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001)) #绑定IP地址和端口号
sock.listen(5)
while True:
thistime=time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime())
try:
connection,address = sock.accept()
connection.settimeout(5)#设置超时间
buf = connection.recv(1024) #设置接收长度
print (thistime+"接收到:"+buf+"")
connection.send(thistime+':'+buf)
except socket.timeout:
print 'time out'
connection.close()
接下来我们就看看客户端的代码:
#coding=gbk
import socket
HOST = 'localhost' #绑定的IP
PORT = 8001 #绑定的端口
while True:
temp=raw_input("输入任意字符发送:")
if temp=="exit":
break
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
strd=temp+""
s.connect((HOST, PORT))
s.send(strd+"")
data = s.recv(1024)
print data
s.close()
这样客户端就能循环地发送输入的字符串.
php的客户端呢:
header ( 'Content-type:text/html;charset=gb2312' );
$host = 'tcp://localhost:8001';
$fp = stream_socket_client($host,$errno, $error,20);
if (! $fp) echo "$error ($errno)";
else
{
fwrite ( $fp, 'sss' );
while ( ! feof ( $fp ) )
{
echo fgets ( $fp ); #获取服务器返回的内容
}
fclose ( $fp );
}
这样服务器和客户机就能通信了,我在本地测试通过.环境py2.6.6+windows xp