#复习一下Tcp 服务端
socket=socket.socket ()
#新建socket
socket.bind()
#绑定端口号
socket.listen()
#监听
cli_socket=socket .accept()
#接受客户端连接
while True:
#进程的方式实现并发。
p=Process(target=fun,args=())
#实现fun函数
p=start()
#开进程
cli_socket.close()
#关闭进程
def fun(cli_socket):
request_data=recv()
#接受请求数据报
HTML_ROOT_DIR='./html'
#创建跟路径
path='/index.html'
#解析请求数据报,提取请求方式,提取请求路径
try:
file = open(HTML_ROOT_DIR+path)
data=file.read()
file.close()
'''
HTTP1.1 200 OK \r\n
\r\n
hello
'''
send()
#发送响应数据
close()
#关闭连接
except IOError:
'''
HTTP1.1 404 NOt Found\r\n
\r\n
not found
'''
# -*- coding: utf-8 -*-
#静态的web服务器
import socket
from multiprocessing import Process
HTML_ROOT_DIR = ""
def handle_client(client_socket):
"""处理客户端请求"""
# 获取客户端请求数据
request_data = client_socket.recv(1024)
print("request data:", request_data)
# 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = "hello itcast"
response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response)
# 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8"))
# 关闭客户端连接
client_socket.close()
if __name__ == "__main__":
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 8000))#绑定一个地址
server_socket.listen(128)#监听
while True:
client_socket, client_address = server_socket.accept()#客户端进行连接时候,这个进行了接受
# print("[%s, %s]用户连接上了" % (client_address[0],client_address[1]))
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 8081 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
while True:
c, addr = s.accept() # 建立客户端连接
print ('连接地址:', addr)
c.send('与服务器连接成功!')
c.close() # 关闭连接
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 8081 # 设置端口号
s.connect((host, port))
print (s.recv(1024))
s.close()