UDP编程

2022-09-08 20:50:24 浏览数 (1)

UDP编程

server.py

代码语言:javascript复制
<span class="hljs-keyword">import</span> socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind((<span class="hljs-string">"10.0.128.226"</span>, <span class="hljs-number">8888</span>))

<span class="hljs-keyword">while</span> <span class="hljs-number">1</span>:
    <span class="hljs-comment"># data:接收到客户端传递的数据</span>
    <span class="hljs-comment"># addr:客户端的IP</span>
    data, addr = server.recvfrom(<span class="hljs-number">1024</span>)
    print(<span class="hljs-string">"收到来自%s的消息:%s"</span>%(addr[<span class="hljs-number">0</span>], data.decode(<span class="hljs-string">"utf-8"</span>)))

client.py

代码语言:javascript复制
<span class="hljs-keyword">import</span> socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
<span class="hljs-keyword">while</span> <span class="hljs-number">1</span>:
    data = input()
    client.sendto(data.encode(<span class="hljs-string">"utf-8"</span>), (<span class="hljs-string">"10.0.128.226"</span>, <span class="hljs-number">8888</span>))

<span class="hljs-comment"># #不建议使用</span>
<span class="hljs-comment"># client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</span>
<span class="hljs-comment"># client.connect(("10.0.128.226", 8888))</span>
<span class="hljs-comment"># while 1:</span>
<span class="hljs-comment">#     data = input()</span>
<span class="hljs-comment">#     client.send(data.encode("utf-8"))</span>

0 人点赞