Python实现socket通信

介绍

本文介绍如何用python脚本实现socket通信,在一台服务器上开一个端口监听,其他机器通过telnet连进来,模仿B/S模式进行通信。

正文

一共两个文件。

webserver.py

import 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<br/>\n" % request.get(‘User-Agent‘, ‘unknown‘)
    r += "You asked for: %s<br/>\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 = False

test.html

<html>    
<head>    
<title>Mooo</title>    
</head>    
<body>    
<h1>Sample file</h1>    
<p>It has some stuff in it.  Maybe even some lists.</p>    
<ul>    
<li>Item 1</li>    
<li>Item 2</li>    
<li>Item 3</li>    
<li>Item 4</li>    
</ul>    
</body>    
</html>

测试

a. 在服务端运行:python webserver.py

[[email protected] socket_lesson]$ python webserver.py
Server listening on port:  8080
End of request found!
Server listening on port:  8080

b. 在另外一台机器上执行:telnet $IP 8080

[[email protected] ~]$ telnet 10.9.214.167 8080
Trying 10.9.214.167...
telnet: connect to address 10.9.214.167: Connection refused
[[email protected] ~]$ 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<br/>
You asked for: /test.html<br/>
Here it is: 
<html>
  <head>
    <title>Mooo</title>
  </head>
  <body>
    <h1>Sample file</h1>
    <p>It has some stuff in it.  Maybe even some lists.</p>
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>
  </body>
</html>
Connection closed by foreign host.

c. 然后输入:GET /test.html HTTP/1.1

这时服务端会把test.html的内容返回。

时间: 2024-08-23 14:34:12

Python实现socket通信的相关文章

Java 和 Python 的 Socket 通信

网络上两个程序通过一个双向通讯连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket支持的协议有多种,这里主要介绍基于 TCP/IP 协议族的 Socket 编程. 首先,IP协议族决定了socket的地址类型,在通信中必须采用对应的地址.AF_INET(AF 表示 Adress Family)表示要用 ipv4 地址(32位)与端口号(16位)的组合. 然后,根据传输协议又分为:流式 Socket(SOCK_STREAM) 和数据报式 Socket(SOCK_DGRAM):

python的socket通信实例

一.socket简介 1. 套接字 套接字是为特定网络协议(例如TCP/IP,ICMP/IP,UDP/IP等)套件对上的网络应用程序提供者提供当前可移植标准的对象. 它们允许程序接受并进行连接,如发送和接受数据.为了建立通信通道,网络通信的每个端点拥有一个套接字对象极为重要. 套接字为BSD UNIX系统核心的一部分,而且他们也被许多其他类似UNIX的操作系统包括Linux所采纳. 许多非BSD UNIX系统(如ms-dos,windows,os/2,mac os及大部分主机环境)都以库形式提供

python基础-socket通信

socket是一种双向通信的起点和重点,氛围服务器端和客户端 Socket服务器端用到的方法有 Method Description s.bind() This method binds address (hostname, port number pair) to socket. s.listen() This method sets up and start TCP listener. s.accept() This passively accept TCP client connectio

Python下socket通信

Server端代码: #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: areful # a server example which send hello to client. import socket import threading import time def tcp_link(_sock, _addr): print('Accept new connection from %s:%s...' % _addr) _sock

Python的socket通信!

# 网络通信服务端 import socket # 1.导入网络通信模块 ip_port = ('0.0.0.0',9898) # 2.制定自身服务器地址和端口 ser = socket.socket() # 3.实例化对象,参数不填默认是ipv4,TCP传输 ser.bind(ip_port) # 4.绑定连接 ser.listen(4) # 5.设置监听,最多允许5个接入 print("开始接入.....") scl,addr = ser.accept() # 6.开始接受连接,阻

python异步socket编程之一

异步网络能极大地提高程序的并行处理能力,所以写了一个专题来总结python中的异步通信. 一.同步client与同步server的通信 1.1. <python的socket通信实例>中的例子 1. TCP server端代码 #!/usr/bin/env python # # -*- coding:utf-8 -*- # File: sync_socket_server.py # from socket import * from time import ctime HOST = '' PO

【Python之旅】第五篇(一):Python Socket通信原理

只要和网络服务涉及的,就离不开Socket以及Socket编程,下面就说说Python Socket通信的基本原理. 1.Socket socket也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络发出请求或者应答网络请求.可以列举中国移动或者是中国电信等的电话客服,当然,也可以看下面的图片来作形象的说明. socket起源于Unix,而Unix/Linux基本哲学之一就是:一切皆文件,即都可以用"打开open-

python - socket通信笔记

参考: 通过编写聊天程序来熟悉python中多线程和socket的用法:https://www.cnblogs.com/mingjiatang/p/4905395.html python socket通信:https://yq.aliyun.com/articles/40745?spm=5176.100239.blogcont40768.17.FIFTZv 1.socket使用方法 a.在python中使用socket时要iamport socket b.在使用socket中又服务器端和客户端之

Python 3 socket编程

Python 3 socket编程 一 客户端/服务器架构 互联网中处处是C/S架构 1.C/S结构,即Client/Server(客户端/服务器)结构 2.在互联网中处处可见c/s架构 比如说浏览器,在线视频,各种社交软件. C/S架构与socket的关系: 我们学习socket就是为了c/s架构的开发 学习socket一定要先学习互联网协议: 1.如何基于socket编程,来开发一款自己的C/S架构软件 2..C/S架构的软件(软件属于应用层)是基于网络进行通信的 3.网络的核心即一堆协议,