python实现socket通信_Python实现socket通信

介绍

本文介绍如何用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

Mooo

Sample 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:

Mooo

Sample 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的内容返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值