百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Python 网络编程基础入门知识篇,欢迎收藏!

toyiye 2024-07-02 02:58 11 浏览 0 评论


Python的网络编程主要支持两种网络协议:TCP和UDP。这两种协议都通过叫Socket的编程抽象进行处理。Socket起源于Unix,是类似于文件的存在,可以像文件一样进行I/O、打开、关闭等操作,最主要的是它可以实现网络上不同主机的进程间通信,所以基本上Socket是任何一种网络通讯中最基础的内容。

Python中建立一个套接字很简单:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. import socket
  2. s = socket.socket(family, type)

</pre>

地址族

family为地址族,该族指定要使用的网络协议,主要使用的有:

  • AF_INET:IPv4协议(TCP,UDP)
  • AF_INET6:IPv6协议(TCP,UDP)
  • AF_UNIX:UNIX域协议,用于同一台机器的进程间通讯

套接字类型

type为套接字类型,指定给定的协议组中使用的通信类型:

  • SOCK_STREAM:用于TCP
  • SOCK_DGRAM:用于UDP

TCP和UDP都是基于Client/Server的编程模型,所以Socket编程也分为客户端和服务器端,以TCP为例:

TCP客户端编程

要获取远程主机的ip地址,可以使用socket标准库提供的gethostbyname方法:

socket套接字实例s可用于客户端的方法有以下几个:

  • s.connect(addr):连接服务器端套接字。addr格式取决于地址族,对于IPv4来说,是一个包含ip地址与端口的元组,(host, port)。连接失败会报socket.error错误。
  • s.sendall(string):尝试发送所有数据,成功则返回None,失败则报异常。
  • s.recv(bufsize):接收数据,bufsize指定接收的最大数据量。
  • s.close:关闭套接字

OK,现在可以用socket向远程主机发送一个HTTP GET请求了:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立套接字
  4. host = 'www.baidu.com'
  5. port = 80
  6. ip = socket.gethostbyname(host) #获取ip
  7. s.connect((ip, port)) #建立连接
  8. message = 'GET / HTTP/1.1rnrn'
  9. s.sendall(message) #发送GET请求
  10. r = s.recv(4096) #接收数据
  11. print r
  12. s.close #关闭套接字

</pre>

返回:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. HTTP/1.1 302 Moved Temporarily
  2. Date: Wed, 10 Jan 2018 18:56:45 GMT
  3. Content-Type: text/html
  4. Content-Length: 225
  5. Connection: Keep-Alive
  6. Location: http://www.baidu.com/search/error.html
  7. Server: BWS/1.1
  8. X-UA-Compatible: IE=Edge,chrome=1
  9. BDPAGETYPE: 3
  10. Set-Cookie: BDSVRTM=0; path=/

</pre>

下面我们可以实现自己的服务器。

TCP服务器端编程

Socket实例与服务器端编程有关的方法有以下几个:

  • s.bind(addr):addr也是(host, port)形式的元组,将套接字绑定到特定的地址和端口上。空字符串表示任意地址,'broadcast'可以用做发送广播信息。
  • s.listen(backlog):开始监听连接,backlog为最大挂起连接次数。
  • s.accept:返回元组(conn,addr),conn为新的套接字,可以用来发送和接收数据。addr是客户端的套接字地址。
  • s.recv、s.sendall和s.close与客户端同。

现在写一个将客户端发送来的信息发送回去的服务器:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. import sys
  4. HOST = ''
  5. PORT = 8088
  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. s.bind((HOST, PORT))
  8. s.listen(5)
  9. print '开始监听'
  10. conn, addr = s.accept
  11. print 'Connected with ' + addr[0] + ':' + str(addr[1])
  12. data = conn.recv(1024)
  13. conn.sendall(data)
  14. conn.close
  15. s.close

</pre>

运行:

服务器开始监听连接了。修改一下刚才写的客户端程序:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  4. host = 'localhost'
  5. port = 8088
  6. s.connect((host, port)) #建立连接
  7. message = 'GET / HTTP/1.1rnrn'
  8. s.sendall(message) #发送GET请求
  9. r = s.recv(4096) #接收数据
  10. print r
  11. s.close #关闭套接字

</pre>

运行,连接本地的服务器,服务器端输出:

连接成功。客户端输出:

发送的消息被返回了。

这就是一个最简单的服务器了。上述服务器只能处理一次连接,这显然不是我们想看到的,保持一直运行:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. import sys
  4. HOST = ''
  5. PORT = 8088
  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. s.bind((HOST, PORT))
  8. s.listen(5)
  9. print '开始监听'
  10. while True:
  11. conn, addr = s.accept
  12. print 'Connected with ' + addr[0] + ':' + str(addr[1])
  13. data = conn.recv(1024)
  14. conn.sendall(data)
  15. conn.close
  16. s.close

</pre>

现在就可以使用客户端无限连接了:

服务器端多线程处理连接

现在服务器端虽然可以处理无限多个连接,但只能一个一个的处理,后面的客户端连接只能等待前面的连接完成才能发送数据。要同时处理多个连接,可以使用多线程。服务器端接收到新的连接后,开启一个线程处理新连接,主线程去建立下一个连接。

服务器端:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. import threading
  4. HOST = ''
  5. PORT = 8088
  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. s.bind((HOST, PORT))
  8. s.listen(5)
  9. print '开始监听'
  10. def runThread(conn):
  11. data = conn.recv(1024)
  12. print data
  13. conn.sendall(data)
  14. conn.close
  15. while True:
  16. conn, addr = s.accept
  17. print 'Connected with ' + addr[0] + ':' + str(addr[1])
  18. t = threading.Thread(target=runThread, args=(conn,))
  19. t.daemon = True
  20. t.start

</pre>

客户端启动多个连接:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. import time
  4. import threading
  5. def run:
  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. host = 'localhost'
  8. port = 8088
  9. s.connect((host, port))
  10. message = 'GET / HTTP/1.1rnrn'
  11. s.sendall(message)
  12. print s.recv(4096)
  13. s.close
  14. if __name__ == '__main__':
  15. for i in xrange(4):
  16. t = threading.Thread(target=run)
  17. t.start

</pre>

运行:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. 开始监听
  2. Connected with 127.0.0.1:61772
  3. GET / HTTP/1.1
  4. Connected with 127.0.0.1:61773
  5. GET / HTTP/1.1
  6. Connected with 127.0.0.1:61774
  7. GET / HTTP/1.1
  8. Connected with 127.0.0.1:61775
  9. GET / HTTP/1.1

</pre>

UDP编程

UDP与TCP的不同之处在于UDP是不用建立连接的。

在此需要使用s.recvfrom与s.sendto方法,前者与s.recv相同,但返回(data, addr)的元组,addr为数据发送端的套接字地址,后者发送数据时需要加入要发送的远程地址。

服务器:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  4. s.bind(('', 10000))
  5. while True:
  6. data, addr = s.recvfrom(1024)
  7. print '接收到%s的连接'%str(addr)
  8. s.sendto(data, addr)

</pre>

客户端:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  4. s.sendto('Hello World', ('localhost', 10000))
  5. r, addr = s.recvfrom(1024)
  6. print r
  7. s.close

</pre>

Python学习关注,免费直播最新课程学习群:839383765 分享业内最新python知识!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码