[Python_7] Python Socket 编程

Posted 山间一棵松

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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链接进来
" % (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
" % (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)

 

 


 

以上是关于[Python_7] Python Socket 编程的主要内容,如果未能解决你的问题,请参考以下文章

pyhs(0.2.4):python2.7+handlersocket

pyhs(0.2.4):python2.7+handlersocket

python_day9_socket

python_day9_socket

python基础学习日志day8-socket上传文件

Python ---- Part 7