码迷,mamicode.com
首页 > 编程语言 > 详细

python socket

时间:2017-10-16 01:41:50      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:socket   sage   def   bind   started   receive   put   ted   received   

server

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import socket


def main():
    host = "127.0.0.1"
    port = 5000

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    print("Server started")
    while True:
        data, addr = s.recvfrom(1024)
        print("Message from: " + str(addr))
        print("From connected user: " + str(data))
        data =  str(data).upper()
        print("Sending: " + str(data))
        s.sendto(bytes(data, "utf-8"), addr)
    s.close()


if __name__ == __main__:
    print("socket server running...")
    main()

 

client

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import socket


def main():
    host = "127.0.0.1"
    port = 5001

    server = ("127.0.0.1", 5000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    message = input("-->")
    while message != "q":
        s.sendto(bytes(message, "utf-8"), server)
        data, addr = s.recvfrom(1024)
        print("Received from server: " + str(data))
        message = input("-->")
    s.close()


if __name__ == __main__:
    main()

 

python socket

标签:socket   sage   def   bind   started   receive   put   ted   received   

原文地址:http://www.cnblogs.com/vickey-wu/p/7675172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!