默认在宿主机开启一个端口,进行访问:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 18:33
# @Author : zhdya
# @File : socket.py
import http.server
import socketserver
port = 8000
host = '127.0.0.1'
address = (host, port)
handle = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(address, handle) as httpd:
print("server start...")
httpd.serve_forever()
多次访问后:
server start...
127.0.0.1 - - [06/Jun/2018 19:34:19] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:34:20] code 404, message File not found
127.0.0.1 - - [06/Jun/2018 19:34:20] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [06/Jun/2018 19:34:24] "GET /client.py HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:34:27] "GET /ssh_client.py HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:35:31] "GET /Server.py HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:35:35] "GET /ssh_server.py HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:37:49] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Jun/2018 19:37:50] "GET / HTTP/1.1" 200 -
socket不支持多并发,socketserver最主要的作用:就是实现一个并发处理,前面只是铺垫。 SocketServer主要是用于解决当多个客户端连接时, Socket服务端都会服务器上创建一个线程或进程来处理该客户端的请求,一个客户端对应一个后端的一个进程或者线程,这样增加系统的利用率。
socketserver就是对socket的再封装。SocketServer模块简化了网络服务器的开发。
import socket
host = 'www.baidu.com'
port = 80
new_ip = socket.gethostbyname(host)
print('Connect to', host, 'is', new_ip)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((new_ip, port))
request = "GET / HTTP/1.1\r\nHost:www.baidu.com\r\n\r\n"
print(type(request))
s.sendall(request.encode("utf-8"))
# python3 sendall发送的不是string,而是bytes python2 要求发送的是string
reply = s.recv(80960)
if reply:
print('ok!')
else:
print('on!')
print(reply)
s.close()
except socket.error as e:
print(e)