异想天开

What's the true meaning of light, Could you tell me why

python中socket编程

日期:2015-06-24 10:32:12
  
最后更新日期:2017-08-29 15:17:30
自己有个python模板,写python脚本时,直接:
[code lang="cpp"]
cp python_template.py python_demo.py
[/code]
然后改写在模板里面添加函数,内容如下:
[code lang="cpp"]
###python_demo.py
#!/usr/bin/python
# encoding: utf-8
#import MySQLdb
import sys
import traceback
import socket

remote_movie_host=''
remote_movie_port=3306
remote_movie_passwd=''
remote_movie_dbname=''
remote_movie_user=''

#remote_db=MySQLdb.connect(host=remote_movie_host,user=remote_movie_user,passwd=remote_movie_passwd,db=remote_movie_dbname,port=remote_movie_port)

def test():
print 'hello world'

def socket_test(ip,port):
socket.setdefaulttimeout(3)
try:
real_send = "GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % 'cosx.me'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print type(sock),"pack buf:",binascii.b2a_hex(send_str),"\nreal_send:",binascii.b2a_hex(real_send)
sock.connect((ip,port))
sock.send(real_send)


recv_str = sock.recv(4096)
if not len(recv_str):
print "recv_str:",len(recv_str)
exit(0)
#print "recv:",binascii.b2a_hex(recv_str),binascii.b2a_hex(recv_str[4:])
print recv_str
sock.close()
return "resp cmd wrong"
except Exception,e:
print e
return "maybe timeout"

if __name__=='__main__':
socket_test('127.0.0.1',80)

[/code]