码迷,mamicode.com
首页 > 编程语言 > 详细

python3.x——socket初步

时间:2017-08-20 00:39:36      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:初步   int   一个   意思   inpu   input   encode   hostname   指定   

  python3.x,socket。


 

  网络请求的本质是socket,俗称套接字。

  以udp为例,通俗来讲时,包括五个流程:

  客户端:

 1 # 通信的五个步骤
 2 
 3 from socket import *
 4 
 5 # 1.选择通信方式
 6 udpSocket = socket(AF_INET, SOCK_DGRAM)
 7 # 2.对方通信地址
 8 sendAddr = ("192.168.10.198", 8080)
 9 # 3.写入数据
10 sendData = bytes(input("请输入要发送的数据:").encode("utf8"))
11 # 4.发送数据
12 udpSocket.sendto(sendData, sendAddr)
13 # 5.关闭通信
14 udpSocket.close()

  服务端:

  

 1 # 服务端,指定端口接收数据
 2 
 3 from socket import *
 4 # 1.选择通信方式
 5 udpSocket = socket(AF_INET, SOCK_DGRAM)
 6 # 2.指定端口接收对方数据
 7 udpSocket.bind((‘‘, 7891))
 8 # 3.解析数据
 9 content, addr = udpSocket.recvfrom(1024)
10 print("%s, %r" % (content.decode("utf8"), addr))
11 # 4.关闭通信
12 udpSocket.close()

  注:  

    1.端口用于指定某个具体的应用。发送数据除了需要知道对方ip地址,还需要知道端口号和数据传输协议。

    2.服务端必须指定该具体应用的端口。客户端不需要。

    3.接收到的数据需要根据协议解析。

  网络通信协议有七层和四层之说。七层是物理层,数据链路层,网络层,传输层,会话层,表示层,应用层。四层是数据层,网络层,传输层,应用层。

  下面这张图很好的解释了socket的发送和接收过程。

  技术分享

  应用层:产生数据

  upd和tcp:数据的两种传输方式,负责将数据和对方端口组包

  ip:将ip地址和数据包继续组包

  就有了(data, (ip, port))

  MAC 硬件接口:组包发送

  然后接收方再一层层解析。

  一次udp通信的过程大致如上。

  socket的通信是双工的,意思是在发送数据的同时,也可以接受数据。

  下面是一个简单的聊天室代码:

  服务端:

 1 from socket import *
 2 
 3 def server():
 4 
 5     udpSocket = socket(AF_INET, SOCK_DGRAM)
 6 
 7     udpSocket.bind((‘‘, 9001))
 8     while True:
 9         content, addr = udpSocket.recvfrom(1024)
10 
11         data = content.decode("gbk")                # decode("utf-8")
12         print(data)
13 
14         sendData = "段小姐:" + str(input("段小姐:"))
15         udpSocket.sendto(sendData.encode("gbk"), addr)      # decode("utf-8")
16     udpSocket.close()
17 
18 if __name__ == "__main__":
19     server()

  客户端:  

 1 from socket import *
 2 
 3 def client():
 4     udpSocket = socket(AF_INET, SOCK_DGRAM)
 5 
 6     while True:
 7         data = "孙先生:"+str(input("孙先生:"))
 8         data = data.encode("gbk")
 9         udpSocket.sendto(data, (gethostbyname(gethostname()), 9001))
10 
11         content, addr = udpSocket.recvfrom(1024)
12         data = content.decode("gbk")                 # decode("utf-8")
13         print(data)
14     # 提示有问题,但能正常运行
15     udpSocket.close()
16 
17 if __name__ == "__main__":
18     client()

  先运行server,再运行client,就可以自嗨了。自嗨的过程如下:

  技术分享 技术分享

  客户端是孙先生,服务端是段小姐。

 

python3.x——socket初步

标签:初步   int   一个   意思   inpu   input   encode   hostname   指定   

原文地址:http://www.cnblogs.com/kuaizifeng/p/7398340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!