客户端编程
#-*- coding:utf8 -*- import socket #创建一个socket #AF_INET指定使用IPv4协议,如果要用更先进的IPv6,就指定为AF_INET6。SOCK_STREAM指定使用面向流的TCP协议 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立连接 s.connect((‘www.sina.com.cn‘, 80)) #发送数据(http请求) s.send(‘GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\n\r\n‘) #接收数据 buffer = [] while True: #每次最多接受1k字节 d = s.recv(1024) if d: buffer.append(d) else: break data = ‘‘.join(buffer) #关闭连接 s.close() #分离http头和主体 header, html = data.split(‘\r\n\r\n‘, 1) print header #把接受到的数据写入文件 with open(‘D:\\sina.html‘, ‘wb‘) as f: f.write(html)
服务器编程
服务器端
#-*- coding:utf8 -*- import socket, threading, time def tcplink(sock, addr): print ‘Accept new connection from %s:%s...‘ %addr sock.send(‘Welcome‘) while True: data = sock.recv(1024) time.sleep(1) if data == ‘exit‘ or not data: break sock.send(‘Hello, %s‘ %data) sock.close() print ‘Connection from %s %s‘ %addr #创建socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #监听端口 s.bind((‘127.0.0.1‘, 9999)) #传入的参数指定等待连接的最大数量 s.listen(5) print ‘Waiting for connection...‘ while True: #接受一个新连接 sock, addr = s.accept() #创建新线程来处理TCP连接 t = threading.Thread(target=tcplink, args=(sock,addr)) t.start()
客户端
#-*- coding:utf8 -*- import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((‘127.0.0.1‘, 9999)) print s.recv(1024) for data in [‘David‘, ‘Yt‘, ‘Amenda‘]: s.send(data) print s.recv(1024) s.send(‘exit‘) s.close()
2015-05-11
时间: 2024-11-05 19:04:09