Python随心记--socket

socket:应用层与TCP/IP协议族通信的中间软件抽象层,是一组接口
  
基于tcp协议的套接字编程
服务端code
#服务端
    #客户端是client.py
import socket

#AF_INET:地址家族
#SOCK_STREAM:居于tcp协议
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.bind(('127.0.0.1',8000))

phone.listen(5)   #最大连接,类似backlog(半连接)模式,用于防止SYN洪水攻击

conn,addr = phone.accept()   #等电话

msg = conn.recv(1024)   #接收消息

print('客户端发来的消息是:%s' %msg)

conn.send(msg.upper())   #发消息

conn.close()

phone.close()

客户端code

#客户端
import socket

phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.connect(('127.0.0.1',8000))

phone.send('hello'.encode('utf-8'))

data = phone.recv(1024)

print('服务端发来的消息是:' ,data)

 

基于tcp协议的套接字编程补充
服务端循环收发消息 
from socket import *

ip_port = ('127.0.0.1',8080)
back_log = 5
buffer_size = 1024

tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)   #重用ip
tcp_server.bind(ip_port)
tcp_server.listen(back_log)

while True:
    conn,addr = tcp_server.accept()
    print('双向连接是:',conn)
    print('客户端地址是:',addr)

    while True:
        try:
            data = conn.recv(buffer_size)
            print('客户端发来的消息:',data.decode('utf8'))
            conn.send(data.upper())
        except Exception:
            break

conn.close()
tcp_server.close()


#客户端clients.py
from socket import *
ip_port = ('127.0.0.1',8080)
back_log = 5
buffer_size = 1024

tcp_client = socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    msg = input('>>>:').strip()
    if not msg:continue
    tcp_client.send(msg.encode('utf8'))
    print('客户端已发消息.............')
    data = tcp_client.recv(buffer_size)
    print('收到服务端返回来的消息',data.decode('utf8'))

tcp_client.close()

 

基于UDP的套接字
#服务端 
import time
from socket import *

ip_port = ('127.0.0.1',8080)
buffer_size = 1024

udp_server = socket(AF_INET,SOCK_DGRAM)

udp_server.bind(ip_port)
while True:
    data,addr = udp_server.recvfrom(buffer_size)   #接收消息
    print(data)
    back_time = time.strftime('%Y-%m-%d %X')
    udp_server.sendto(data.upper(),addr)   #发消息
    udp_server.sendto(back_time.upper(),addr)   #发消息



#客户端 udp_client.py
from socket import *

ip_port = ('127.0.0.1',8080)
buffer_size = 1024

udp_client = socket(AF_INET, SOCK_DGRAM)

while True:
    msg = input('>>>>:').strip()
    udp_client.sendto(msg.encode('utf8'),ip_port)  #发消息

    data,addr = udp_client.recvfrom(buffer_size)   #接收消息

    print(data)

 

基于tcp实现远程执行命令
#服务端  

from socket import *
import subprocess
import struct
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)

while True:
    conn,addr=tcp_server.accept()
    print('新的客户端链接',addr)
    while True:
        #
        try:
            cmd=conn.recv(buffer_size)
            if not cmd:break
            print('收到客户端的命令',cmd)

            #执行命令,得到命令的运行结果cmd_res
            res=subprocess.Popen(cmd.decode('utf-8'),shell=True,
                                 stderr=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE)
            err=res.stderr.read()
            if err:
                cmd_res=err
            else:
                cmd_res=res.stdout.read()

            #
            if not cmd_res:
                cmd_res='执行成功'.encode('gbk')

            length=len(cmd_res)

            data_length=struct.pack('i',length)
            conn.send(data_length)
            conn.send(cmd_res)
        except Exception as e:
            print(e)
            break

客户端:tcp_client.py
from socket import *

ip_port = ('127.0.0.1',8080)
back_log = 5
buffer_size = 1024

tcp_client = socket(AF_INET,SOCK_STREAM)
tcp_client.bind(ip_port)
tcp_client.listen(back_log)

while True:
    cmd = input('>>>>>:').strip()
    if not cmd:
        continue
    if cmd == 'quit':
        break
    tcp_client.send(cmd.encode('utf-8'))
    cmd_res = tcp_client.recv(buffer_size)
    print('命令的执行结果是:',cmd_res.decode('gbk'))
tcp_client.close()

 

posted @ 2019-01-05 13:16  爱跑步的乌龟  阅读(154)  评论(0编辑  收藏  举报