Python Socket Python 网络编程起步(Socket发送消息)
人气:0想了解Python 网络编程起步(Socket发送消息)的相关内容吗,在本文为您仔细讲解Python Socket的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,网络编程,下面大家一起来学习吧。
一、服务端(Server.py)服务端要做的事情是:
1. 创建一个Socket对象
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2. 绑定一个端口s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 8081))
3. 接受来自客户端的消息while True:
# Receive up to 1,024 bytes in a datagram
data, addr = s.recvfrom(1024)
print "Received:", data, "from", addr
二、客户端(Client.py)# Receive up to 1,024 bytes in a datagram
data, addr = s.recvfrom(1024)
print "Received:", data, "from", addr
客户端要做的事情是:
1. 创建一个Socket对象。
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2. 向某个服务器的指定的端口发送消息。由于使用UDP,如果服务器端未接收到将会丢弃数据包。s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = 8081
host = "localhost"
while True:
msg = raw_input()
s.sendto(msg, (host, port))
三、运行试试host = "localhost"
while True:
msg = raw_input()
s.sendto(msg, (host, port))
加载全部内容