Python Socket通信例子

一、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(b'bye')
            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(b'bye')
        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(b'bye', 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()
原文地址:https://www.cnblogs.com/yueyun00/p/9996853.html