1. 程式人生 > >[Python_7] Python Socket 程式設計

[Python_7] Python Socket 程式設計


 

0. 說明

  Python Socket 程式設計

 


 

1. TCP 協議

  [TCP Server]

  通過 netstat -ano 檢視埠是否開啟

# -*-coding:utf-8-*-

"""
    TCP 協議的 Socket 程式設計,Server 端
    Server 端繫結到指定地址,監聽特定的埠,接受發來的連線請求
"""
import threading
import socket
import time


class CommThread(threading.Thread):
    def
run(self): while True: # 接受資料 data = sock.recv(4096) print("收到了%s = %s" % (str(self.addr), str(data)), ) def __init__(self, sock, addr): threading.Thread.__init__(self) self.sock = sock self.addr = addr # 建立伺服器套接字,繫結埠 ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ss.bind((
"127.0.0.1", 8888)) ss.listen(0) while True: sock, addr = ss.accept() CommThread(sock, addr).start() print("%s連結進來\r\n" % (str(addr)), ) time.sleep(1)

 

  [TCP Client]

 

# -*-coding:utf-8-*-
"""
    TCP 協議的 Socket 程式設計,Client 端
"""
import threading
import socket
import
time # 建立伺服器套接字,繫結埠 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1" , 8888)) i = 1 while True: str = "tom%d\r\n" % (i) print ("client : " + str), sock.send(bytes(str,'utf-8')) time.sleep(1) i += 1

 

 


 

2. UDP 協議

  [UDP Server]

 

# -*-coding:utf-8-*-

"""
    UDP 協議的 Socket 程式設計,Server 端
"""
import socket

# 建立 UDP 接收方
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("192.168.13.6", 9999))

i = 1
while True:
    data = sock.recv(4096)
    print(str(data))

 

  [UDP Client]

 

# -*-coding:utf-8-*-
"""
    UDP 協議的 Socket 程式設計,Client 端
"""

import socket
import time

# 建立 UDP 傳送方
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("192.168.13.6", 8888))

i = 1
while True:
    sock.sendto(bytes(("tom" + str(i)),'utf-8'), ("192.168.13.255", 9999))
    i += 1
    time.sleep(1)