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

Python Socket通信例子

时间:2018-11-21 19:33:16      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:server   python   ram   nbsp   close   bytes   lis   strong   net   

一、TCP 通信 

  • 服务端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# server_tcp.py

import socket

so = socket.socket()
so.bind((127.0.0.1, 8080))
so.listen()

while True:
    conn, addr = so.accept()

    while True:
        ret = conn.recv(1024).decode(utf-8)
        print(ret)
        if ret == bye:
            break
        msg = input("请输入<<< ")
        if msg == bye:
            conn.send(bbye)
            break

        conn.send(bytes(msg, encoding=utf-8))

    conn.close()

so.close()
  • 客户端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# client_tcp.py

import socket

so = socket.socket()
so.connect((127.0.0.1, 8080))

while True:
    msg = input("请输入<<< ")
    if msg == bye:
        so.send(bbye)
        break
    so.send(bytes(msg, encoding=utf-8))
    ret = so.recv(1024).decode(utf-8)
    print(ret)
    if ret == bye:
        break

 二、UDP通信

  • 服务端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# server_udp.py

import socket

so = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
so.bind((127.0.0.1, 8080))

while True:
    ret, addr = so.recvfrom(1024)
    print(ret.decode(utf-8), addr)

    msg = input("请输入<<< ")
    so.sendto(bytes(msg, encoding=utf-8), addr)

so.close()
  • 客户端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# client_udp.py

import socket

so = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip_port = (127.0.0.1, 8080)

while True:
    msg = input("请输入<<< ")
    if msg == bye:
        so.sendto(bbye, ip_port)
        break
    so.sendto(bytes(msg, encoding=utf-8), ip_port)
    ret, addr = so.recvfrom(1024)
    print(ret.decode(utf-8), addr)
    if ret == bye:
        break

so.close()

 

Python Socket通信例子

标签:server   python   ram   nbsp   close   bytes   lis   strong   net   

原文地址:https://www.cnblogs.com/yueyun00/p/9996853.html

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