网络编程从大的方面说就是对信息的发送到接收,中间传输为物理线路的作用。

它的含义是使用套接字来达到进程间的通信。套接字可以看成是两个网络应用程序进行通信时,各自通信连接中的一个端点。

套接字Socket=(IP地址:端口号)

端口号是区分不同的程序,因为一台电脑只有一个IP地址。

一般的网络系统提供了三种不同类型的套接字,以供用户在设计网络应用程序时根据不同的要求来选择。

  • 流式套接字(SOCK-STREAM):提供可靠的、面向连接的双向数据传输服务,实现了数据无差错、无重复的发送。内设流量控制,被传输的数据看作是无记录边界的字节流。(TCP
  • 数据报套接字(SOCK-DGRAM):提供无连接、不可靠的双向数据传输服务。(UDP
  • 原始套接字(SOCK-RAW):该套接字允许对较低层协议(如IP或者ICMP)进行直接访问。
kNuzxa.png

Socket工作流程

Python中提供socket.py标准库,非常底层的接口库。Socket是一种通用的网络编程接口,和网络层次没有一一对应关系。

Functions:

(1)socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

​ Create a new socket using the given address family,socket type and protocol number.

  • main family:
名称 含义
AF_INET(默认) IPV4
AF_INET6 IPV6
AF_UNIX Unix Domain Socket,windows没有
  • type:
名称 含义
SOCK_STREAM(默认) 流式套接字
SOCK-DGRAM 数据报套接字
SOCK-RAW 原始套接字
  • protocol number

协议号通常为零,可以省略,或者在地址族为AF_CAN的情况下,协议应为CAN_RAW或CAN_BCM之一。


Socket Objects

socket.bind(address)

​ Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family )

​ 其中address为元祖,(IP,端口)

socket.listen([backlog])

​ Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.

简单来说,这里的backlog表示socket的”排队个数“

一般情况下,一个进程只有一个主线程(也就是单线程),那么socket允许的最大连接数为: backlog+ 1
如果服务器是多线程,比如上面的代码例子是开了2个线程,那么socket允许的最大连接数就是: backlog+ 2
换句话说:排队的人数(就是那个n) + 正在就餐的人数(服务器正在处理的socket连接数) = 允许接待的总人数(socket允许的最大连接数)

socket.accept()

​ Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

​ 该方法阻塞等待客户端建立连接。

socket.recv(bufsize[, flags])

​ Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

socket.send(bytes[, flags])

​ Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO.

socket.close()

​ Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from makefile() are closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed).

​ Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them.

简单例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#
'''
# socket _server
'''
# =================================================

# -*-coding:utf-8-*-
# 服务器端
import socket

server = socket.socket()
server.bind(('localhost', 6969)) # 绑定要监听端口
server.listen(5) # 监听

print("我要开始等电话了")

while True:
conn, addr = server.accept() # 等电话打进来

# conn就是客户端连过来而在服务器端为其生成的一个连接实例
print(conn, addr)
print("电话来了")

count = 0

while True:
data = conn.recv(1024)

print("recv:", bytes.decode(data))

if not data:
print("client has lost...")
break
conn.send(data.upper())

count += 1
if count > 10:
print('count %', count)
break

server.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#
'''
#socket client
'''

# 客户端
import socket

client = socket.socket() # 声明socket类型,同时生成socket连接对象

client.connect(('localhost', 6969))

while True:
msg = input(">>:").strip()

if len(msg) == 0:
print('not message')
continue

client.send(msg.encode("utf-8"))
data = client.recv(10240)

print("Receive:", bytes.decode(data))

client.close()

结果:

kN8Evy.png

服务端

kNAgj7.png

客户端

相关文章
评论
分享
  • java实现类FTP程序

    继承程序设计实验,实验说明如图所示: 集成程序设计实验 TCP实现首先说明下基于TCP实现的功能: (1)能够实现多用户的同时连接 (2)用户执行成功的命令会在其他用户终端上显式说明 (3)当前用户数以及在线情况会在服务端实时显...

    java实现类FTP程序
  • Centos安装

    虚拟机下载及安装1.进入VMware官网,转到下载页面 https://my.vmware.com/cn/web/vmware/info/slug/desktop_end_user_computing/vmware_workstati...

    Centos安装
  • Windows下neo4j的安装

    neo4j是一个高性能的NOSQL图形数据库,他将结构化数据存储在网络上而不是表中。他是一个嵌入式的、基于磁盘的、具备完全的事物特性的Java持久化引擎,neo4j也可看做是一个高性能的图引擎,该引擎具有成熟数据库的所有特性。——百度...

    Windows下neo4j的安装
  • Java中的流

    流是个抽象的概念,是对输入输出设备的抽象,Java程序中,对于数据的输入输出都是以流的方式进行。设备可以是文件、网络、内存等。 I/O字节流InputStream字节输入流OutputStream字节输出流用于以字节的形式读取和写入数...

    Java中的流
  • eclipse使用

    Eclipse是一个开放源代码的、基于Java的可拓展开发平台。 常用快捷键 快捷键 作用 alt+/ 代码快速补全 ctrl+1 快速修复 ctrl+shift+f 代码格式化 ctrl+d 删除一行代码 ...

    eclipse使用
  • JavaEE开发准备

    个人电脑硬件配置: Windows 10 64位家庭中文版 8G运行内存 Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz 1.Java JDK安装及配置(1)下载和安装首先进入oracle网站中Ja...

    JavaEE开发准备
  • Python进阶学习

    假期补习补习Python,防止以后用到炸锅。 闭包在Python语言中,一切皆对象。 闭包:一个函数定义中引用了函数外定义的变量,并且该函数可以在其定义环境外被执行。 闭包 = 函数 + 环境变量 123456789101...

    Python进阶学习
  • 推荐算法研究(一)

    推荐算法大体分为3类:基于系统过滤的推荐、基于内容的推荐、混合推荐 1.基于协同过滤的推荐系统(Collaborative Filtering)使用行为数据,利用集体智慧来推荐。属于有监督学习。基于用户的协同过滤(找和你兴趣相似的人所...

    推荐算法研究(一)
  • dart中HTTP请求的处理

    dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等… ,最重要的是国人开发,牛皮。 (1)添加dio库 找到项目中的pu...

    dart中HTTP请求的处理
  • dart底部导航栏的简单编写

    底部导航栏目前在手机应用中非常常见,可见其对于软件设计来说非常的有必要和重要。下面简单总结使用flutter和dart如何实现底部导航栏的制作。 首先值得注意的是底部导航栏为动态的组件,所以继承的话应该是StatefulWidget类...

    dart底部导航栏的简单编写
Please check the comment setting in config.yml of hexo-theme-Annie!