python实现简单socket程序在两台电脑之间传输消息的方法

1127次阅读  |  发布于5年以前

本文实例讲述了python实现简单socket程序在两台电脑之间传输消息的方法。分享给大家供大家参考。具体分析如下:

python开发简单socket程序在两台电脑之间传输消息,分为客户端和服务端,分别在两台电脑上运行后即可进行简单的消息传输,也可以在一台电脑上测试,设置两个不同的端口即可。


    # Save as server.py 服务端代码
    # Message Receiver
    import os
    from socket import *
    host = ""
    port = 13000
    buf = 1024
    addr = (host, port)
    UDPSock = socket(AF_INET, SOCK_DGRAM)
    UDPSock.bind(addr)
    print "Waiting to receive messages..."
    while True:
      (data, addr) = UDPSock.recvfrom(buf)
      print "Received message: " + data
      if data == "exit":
        break
    UDPSock.close()
    os._exit(0)

    # Save as client.py 客户端代码
    # Message Sender
    import os
    from socket import *
    host = "127.0.0.1" # set to IP address of target computer
    port = 13000
    addr = (host, port)
    UDPSock = socket(AF_INET, SOCK_DGRAM)
    while True:
      data = raw_input("Enter message to send or type 'exit': ")
      UDPSock.sendto(data, addr)
      if data == "exit":
        break
    UDPSock.close()
    os._exit(0)

希望本文所述对大家的Python程序设计有所帮助。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8