- 论坛徽章:
- 0
|
要是我是你,我会这么写,加上一些异常保护:- import socket,sys
- host=sys.argv[1]
- textport=sys.argv[2]
- s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
- try:
- port=int(textport)
- except ValueError:
- port=socket.getservbyname(textport,'udp')
- s.connect((host,port))
- print 'Enter data to transmit: '
- data=sys.stdin.readline().strip()
- #发送数据
- try:
- s.sendall(data)
- except socket.error, e:
- print 'Error sending data:%s' % e
- sys.exit(1)
- print 'Looking for replies;press Ctrl-C or Ctrl-Break to stop'
- #清除缓存内容
- try:
- s.shutdown(1)
- except socket.error, e:
- print 'Error sending data:%s' % e
- sys.exit(1)
- #接收数据循环
- while True:
- try:
- buf = s.recv(2048) #接收数据
- except socket.error, e:
- print 'Error receiving data:%s' % e
- sys.exit(1)
- if not len(buf):
- break
- sys.stdout.write(buf)
复制代码 |
|