TCP/UDP套接字通信

一,基于TCP套接字通信

服务端

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

phone.bind(('127.0.0.1',8081))
phone.listen(5)

print('准备监听')
conn,client_addr=phone.accept()
print(client_addr)

while True:
    try:
        data=conn.recv(1024)
        if len(data)==0:break    #如果不加该条件,当客户端非法断开链接,意味着异常行为,针对unix系统死循环现象
        print('客户端发的消息:',data.decode('utf-8'))
        conn.send(data.upper())
    except Exception:
        break         #如果不加该条件,当客户端非法断开链接,意味着异常行为,针对于winodws系统的直接报错


conn.close()

phone.close()

客户端

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

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

while True:
    msg=input("要输入的内容:".strip())
    if len(msg)==0:continue      # if not msg:continue,如果不加该条件,输入空信息会导致客户端停在原地
    phone.send(msg.encode('utf-8'))
    data=phone.recv(1024)
    print(data.decode('utf-8'))

phone.close()

服务端
客户端1
客户端2

二,基于UDP套接字通信

服务端

from socket import *
server=socket(AF_INET,SOCK_DGRAM)

server.bind(('127.0.0.1',8087))

while True:
    data,client_addr=server.recvfrom(1024)
    # 客户端client.sendto(msg.encode('utf-8'),('127.0.0.1',8087)),所以这里定义两个值data,client_addr
    server.sendto(data.upper(),client_addr)

server.close()

客户端

from socket import *
client=socket(AF_INET,SOCK_DGRAM)


while True:
    msg=input('>>>>').strip()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8087))
    data=client.recvfrom(1024)
    print(data)

client.close()


- 执行如下(服务端无返回信息)

>>>>p
(b'P', ('127.0.0.1', 8087))
>>>>ls
(b'LS', ('127.0.0.1', 8087))
客户端,纠正!!!UDP先启动任意一端都可以

三,实现远程执行命令

客户端

from socket import *
client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8083))

while True:
    cmd=input('>>>>').strip()
    if len(cmd)==0:continue
    client.send(cmd.encode('utf-8'))
    data=client.recv(1024)
    print(data.decode('utf-8'))

服务端

from socket import *
import subprocess

server=socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)    #端口复用,防止测试总报错端口占用
server.bind(('127.0.0.1',8083))

server.listen(5)
# 第一件事:循环的从链接池中取出链接请求并建立双向链接,拿到链接对象
while True:
    conn,client_ip=server.accept()
    # 拿到链接对象,进行通话循环
    while True:
        try:
            data=conn.recv(1024)            #易错,是conn.revc,不是server.revc(conn相当于一条桥梁)
            if len(data)==0:break
            msg=subprocess.Popen(data.decode('utf-8'),
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            res_stdout=msg.stdout.read()
            res_stderr=msg.stderr.read()
            print((res_stdout+res_stderr).decode('utf-8'))
            conn.send(res_stdout+res_stderr)
        except Exception:
            break
    conn.close()

服务端

你可能感兴趣的:(TCP/UDP套接字通信)