1. 程式人生 > >Python Socket通訊例子

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()