介绍
本文介绍如何用python脚本实现socket通信,在一台服务器上开一个端口监听,其他机器通过telnet连进来,模仿B/S模式进行通信。
正文
一共两个文件。
webserver.pyimport socket
import re
import os
PORT = 8080
# Create a Server Socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', PORT))
serversocket.listen(5) # Open socket for listening, max of 5 connections
# Take a request "string"
def process_request(reqdata):
request_headers = {}
# Loop through each line and record the request headers
for line in reqdata.split("\r\n"):
# If the line contains a colon, it's a header
if (line.find(':') != -1):
(key, value) = line.split(": ", 1)
request_headers[key] = value
# Maybe it's a GET request...
elif (line.find("GET") != -1):
location = re.findall(r'^GET (.*) HTTP/.*', line)
if len(location):
request_headers['GET'] = location[0]
return request_headers
# Get a response
def process_response(request):
r = "HTTP/1.0 200 OK\n"
r += "Content-type: text/html\n\n"
url = request.get('GET', '/index.html')
r += "You're running: %s
\n" % request.get('User-Agent', 'unknown')
r += "You asked for: %s
\n" % url
if os.path.isfile("." + url):
r += "Here it is: \n"
f = open("." + url)
r += f.read()
return r
while True:
print "Server listening on port: ", PORT
connection, address = serversocket.accept()
running = True
data = ""
while running:
buf = connection.recv(1024)
requestdone = False
if len(buf) > 0:
data += buf
if buf.find("\r\n") != -1:
requestdone = True
print "End of request found!"
else:
print "read: '%s'" % buf
if requestdone:
# Data should now contain a string of the entire request
request = process_request(data)
connection.send(process_response(request));
# Disconnect our client
connection.close()
running = False
else:
running = Falsetest.html
MoooSample file
It has some stuff in it. Maybe even some lists.
- Item 1
- Item 2
- Item 3
- Item 4
测试
a. 在服务端运行:python webserver.py
[hadoop@hadoop-zookeeper1-503500 socket_lesson]$ python webserver.py
Server listening on port: 8080
End of request found!
Server listening on port: 8080
b. 在另外一台机器上执行:telnet $IP 8080[hadoop@hadoopslave3 ~]$ telnet 10.9.214.167 8080
Trying 10.9.214.167...
telnet: connect to address 10.9.214.167: Connection refused
[hadoop@hadoopslave3 ~]$ telnet 10.9.214.167 8080
Trying 10.9.214.167...
Connected to 10.9.214.167.
Escape character is '^]'.
GET /test.html HTTP/1.1
HTTP/1.0 200 OK
Content-type: text/html
You're running: unknown
You asked for: /test.html
Here it is:
MoooSample file
It has some stuff in it. Maybe even some lists.
- Item 1
- Item 2
- Item 3
- Item 4
Connection closed by foreign host.
c. 然后输入:GET /test.html HTTP/1.1
这时服务端会把test.html的内容返回。