通过本文主要向大家介绍了python socket编程,python3 socket编程,python socket,python socket模块,python socketserver等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
一、服务端(Server.py)
服务端要做的事情是:
1. 创建一个Socket对象
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</div> 2. 绑定一个端口
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
s.bind(("", 8081))</div> 3. 接受来自客户端的消息
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
while True:
# Receive up to 1,024 bytes in a datagram
data, addr = s.recvfrom(1024)
print "Received:", data, "from", addr</div>二、客户端(Client.py)
客户端要做的事情是:
1. 创建一个Socket对象。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</div> 2. 向某个服务器的指定的端口发送消息。由于使用UDP,如果服务器端未接收到将会丢弃数据包。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
port = 8081
host = "localhost"
while True:
msg = raw_input()
s.sendto(msg, (host, port))</div>三、运行试试
</div>
服务端要做的事情是:
1. 创建一个Socket对象
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</div> 2. 绑定一个端口Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
s.bind(("", 8081))</div> 3. 接受来自客户端的消息Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
while True:
# Receive up to 1,024 bytes in a datagram
data, addr = s.recvfrom(1024)
print "Received:", data, "from", addr</div>二、客户端(Client.py)客户端要做的事情是:
1. 创建一个Socket对象。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</div> 2. 向某个服务器的指定的端口发送消息。由于使用UDP,如果服务器端未接收到将会丢弃数据包。Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
port = 8081
host = "localhost"
while True:
msg = raw_input()
s.sendto(msg, (host, port))</div>三、运行试试
</div>

