1.python写法
import sys
import socket
import argparse
def main():
# setup argument parsing
parser = argparse.ArgumentParser(description='Socket Error Examples')
parser.add_argument('--host', action="store", dest="host", required=False)
parser.add_argument('--port', action="store", dest="port", type=int, required=False)
parser.add_argument('--file', action="store", dest="file", required=False)
given_args = parser.parse_args()
host = given_args.host
port = given_args.port
filename = given_args.file
# First try-except block -- create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" % e
sys.exit(1)
# Second try-except block -- connect to given host/port
try:
s.connect((host, port))
except socket.gaierror, e:
print "Address-related error connecting to server: %s" % e
sys.exit(1)
except socket.error, e:
print "Connection error: %s" % e
sys.exit(1)
# Third try-except block -- sending data
try:
s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error, e:
print "Error sending data: %s" % e
sys.exit(1)
while 1:
# Fourth tr-except block -- waiting to receive data from remote host
try:
buf = s.recv(2048)
except socket.error, e:
print "Error receiving data: %s" % e
sys.exit(1)
if not len(buf):
break
# write the received data
sys.stdout.write(buf)
if __name__ == '__main__':
main()
getMessage());
}
# Fourth tr-except block -- waiting to receive data from remote host
while (1) {
if (false !== ($bytes = socket_recv($socket, $file, 2048, MSG_WAITALL))) {
printf("Read %s bytes from socket_recv(). Closing socket...", $bytes);
} else {
printf("Error receiving data: %s\n" . socket_strerror(socket_last_error($socket)));
}
}
python如果提示argparse这个库没有的话,请使用pip install argparse来安装,php我在pecl上搜了下,php貌似没有想python的argparse这样的库,据说pear有个叫command line的包,不过我没有试过,毕竟 php直接以php-cli方式运行的情况不多,所以这个功能对于php也没有多大的意义,以变量代替吧~
python对于socket的错误捕捉,已经有现成的Exception class,而php可以使用socket_last_error来捕捉错误,try catch到Exception类也可以有相关提示,但是socket_last_error会更具体~
转载请标注原文地址:http://blog.csdn.net/ddjohn/article/details/49992391