Python 网络编程起步(Socket发送消息)
Python 网络编程起步(Socket发送消息)
发布时间:2016-12-28 来源:查字典编辑
摘要:一、服务端(Server.py)服务端要做的事情是:1.创建一个Socket对象importsockets=socket.socket(so...

一、服务端(Server.py)

服务端要做的事情是:

1. 创建一个Socket对象

Python 网络编程起步(Socket发送消息)1importsocket

Python 网络编程起步(Socket发送消息)1s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 2. 绑定一个端口

Python 网络编程起步(Socket发送消息)1s.bind(("",8081)) 3. 接受来自客户端的消息

Python 网络编程起步(Socket发送消息)1whileTrue:

Python 网络编程起步(Socket发送消息)1#Receiveupto1,024bytesinadatagram

Python 网络编程起步(Socket发送消息)1data,addr=s.recvfrom(1024)

Python 网络编程起步(Socket发送消息)1print"Received:",data,"from",addr二、客户端(Client.py)

客户端要做的事情是:

1. 创建一个Socket对象。

Python 网络编程起步(Socket发送消息)1importsocket

Python 网络编程起步(Socket发送消息)1s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 2. 向某个服务器的指定的端口发送消息。由于使用UDP,如果服务器端未接收到将会丢弃数据包。

Python 网络编程起步(Socket发送消息)1port=8081

Python 网络编程起步(Socket发送消息)1host="localhost"

Python 网络编程起步(Socket发送消息)1whileTrue:

Python 网络编程起步(Socket发送消息)1msg=raw_input()

Python 网络编程起步(Socket发送消息)1s.sendto(msg,(host,port))三、运行试试

Python 网络编程起步(Socket发送消息)2

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新python学习
热门python学习
脚本专栏子分类