Socket实例

Socket实例


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

host = '127.0.0.1'
port = 80

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')

buffer = []

while True:
    d = s.recv(1024)
    if not d:
        break
    buffer.append(d)

data = b''.join(buffer)

s.close()

print(data)

服务器端


# Python 3

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):

	def handle(self):
		self.data = self.request.recv(1024)
		respone = b'HTTP/1.1 200 OK\r\n\r\nOK'
		self.request.send(respone)

if __name__ == "__main__":
	server = socketserver.ThreadingTCPServer(('0.0.0.0', 8000), MyTCPHandler)
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		pass
	server.server_close()
	print('Bye')