1、网络通信概述
1.1 网络的定义
网络:辅助双方或者多方能够连接在一起的工具,用来进行数据交换
协议:约定俗成的规定
tcp/ip协议:计算机遵守的网络通信协议
1.2 端口
个数:2的16次方(65536)(0-65535)
端口是数据发出或接收的入口
端口的目的:通过端口号找到对应的进程,完成数据的通信
著名端口0-1023
动态端口:2014-65535
1.3 IP
IP地址:标注在网络中标记一台计算机的一串数字,例如192.168.24.1 ,在本地局域网上是唯一的
注意:127.0.0.1 代表的是本机的IP地址
2、socket
简称:套接字,是进程之间进行通信的一种方式
实现了不同主机之间的进程通信,我们现在使用的大多数的服务:qq、浏览网页等基于socket来完成通信的
2.1 python 中socket
def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
# For user code address family and type values are IntEnum members, but
# for the underlying _socket.socket they're just integers. The
# constructor of _socket.socket converts the given argument to an
# integer automatically.
_socket.socket.__init__(self, family, type, proto, fileno)
self._io_refs = 0
self._closed = False
注意点:
1、family=AF_INET,表示的用于Internet之间的通信
2、type=SOCK_STREAM,是指流式套接字,用于tcp协议
3、type=SOCK_DGRAM数据报套接字,用于udp协议
2.2 udp发送数据
def sendto(self, data, flags=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
sendto(data[, flags], address) -> count
Like send(data, flags) but allows specifying the destination address.
For IP sockets, the address is a pair (hostaddr, port).
"""
pass
注意点:
1、sendto()这个方法发送的数据,是bytes类型,普通字符串用encode()转化成bytes
2、address 用来指定对方的IP和端口,打包成元组
2.3 udp接收数据
def recvfrom(self, buffersize, flags=None): # real signature unknown; restored from __doc__
"""
recvfrom(buffersize[, flags]) -> (data, address info)
Like recv(buffersize, flags) but also return the sender's address info.
"""
pass
注意点:
1、返回值,返回(数据,发送该条信息的地址)
2、数据接收过来是bytes类型的,需要用decode()转换成普通的字符串
2.4 bind端口
def bind(self, address): # real signature unknown; restored from __doc__
"""
bind(address)
Bind the socket to a local address. For IP sockets, the address is a
pair (host, port); the host must refer to the local host. For raw packet
sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
"""
pass
socket_udp_client.bind(('',9000))
''代表本机的任何一个地址都可以
3、 UDP协议
3.1 特点
面向无连接的通讯协议
3.2 udp服务端的通信流程
1、创建一个socket套接字
2、绑定端口
3、接收服务端传递过来的请求
4、处理请求,发送数据给客户端
5、关闭套接字
3.3 UDP 客户端通信流程
1、创建套接字
2、发送请求(数据)
3、接收数据
4、关闭套接字