返回顶部

day30 socket

 

客户端异常断开

import  socket
ip_addr = ("127.0.0.1",1234)
bufsize = 1024

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(ip_addr)
while True:
    msg = input(">>>>>>>>>").strip()
    s.send(msg.encode("utf-8"))
    data = s.recv(bufsize)
    print(data.decode("utf-8"))
s.close()
client
import  socket
ip_addr = ("127.0.0.1",1234)
bufsize = 1024
backlog = 5

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip_addr)
s.listen(backlog)

while True:
    print("连接开始")
    conn, addr = s.accept()
    print(addr)
    while True:
        try:
            data = conn.recv(bufsize)
            print("客户端信息",data.decode("utf-8"))
            msg = input(">>>>>>  ").strip()
            conn.send(msg.encode("utf-8"))
        except ConnectionResetError:
            break
    conn.close()
s.close()
server

 

客户端输入为空的时候继续输入

import  socket
ip_addr = ("127.0.0.1",1234)
bufsize = 1024
backlog = 5

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip_addr)
s.listen(backlog)


while True:
    conn,addr = s.accept()
    print(addr)
    while True:
        try:
            data =  conn.recv(bufsize)
            print("客户端发来的数据",data.decode("utf-8"))
            msg = input(">>>>>>>: ").strip()
            if len(msg) == 0: continue
            conn.send(msg.encode("utf-8"))
        except ConnectionResetError:
            break
    conn.close()
s.close()
server
import  socket
ip_addr = ("127.0.0.1",1234)
bufsize = 1024

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(ip_addr)

while True:
    msg = input(">>>>>>>>>>>>>   ").strip()
    if len(msg) ==0 :continue
    s.send(msg.encode("utf-8"))
    data = s.recv(bufsize)
    print("服务器端发来的数据",data.decode("utf-8"))
s.close()
client

 

udp时间服务器

import socket,time
ip_addr = ("127.0.0.1",2222)
buffersize = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(ip_addr)

while True:
    data,addr = s.recvfrom(buffersize)
    print(data)
    if not data:
        fmt = "%Y-%m-%d %X"
    else:
        fmt = data.decode("utf-8")
    back_time = time.strftime(fmt)
    s.sendto(back_time.encode('utf-8'), addr)
服务端
import socket
ip_addr = ("127.0.0.1",2222)
buffersize = 1024
c = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while True:
    msg = input(">>>>>>>>>>>>>>>").strip()
    c.sendto(msg.encode("utf-8"),ip_addr)
    data,addr = c.recvfrom(buffersize)
    print("标准时间为:   ",data.decode("utf-8"))
客户端

 

socket 远程执行命令

#encoding:utf-8
from socket import *
import  subprocess

ip_port = ("127.0.0.1",1111)
BUFSIZE=1024
tcp_socket_server=socket(AF_INET,SOCK_STREAM)
tcp_socket_server.bind(ip_port)
tcp_socket_server.listen(5)

while True:
    conn,addr = tcp_socket_server.accept()
    print("客户端",addr)
    while True:
        try:
            cmd = conn.recv(BUFSIZE)
            if len(cmd) == 0:break
            #执行命令, 得到命令的运行结果cmd_res
            res= subprocess.Popen(cmd.decode("utf-8"),shell=True,
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
            err = res.stderr.read()
            if err:
                cmd_res = err
            else:
                cmd_res = res.stdout.read()
            conn.send(cmd_res)
        except Exception as e:
            print(e)
            break
    conn.close()
server
import socket
BUFSIZE=1024
ip_port=('127.0.0.1',1111)

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
res=s.connect_ex(ip_port)

while True:
    msg=input('>>: ').strip()
    if len(msg) == 0:continue
    if msg == 'quit':break
    s.send(msg.encode('utf-8'))
    act_res=s.recv(BUFSIZE)
    print(act_res.decode('gbk'),end='')
client

 

low解决粘包问题

#encoding:utf-8
from socket import *
import  subprocess

ip_port = ("127.0.0.1",1111)
BUFSIZE=1024
tcp_socket_server=socket(AF_INET,SOCK_STREAM)
tcp_socket_server.bind(ip_port)
tcp_socket_server.listen(5)

while True:
    conn,addr = tcp_socket_server.accept()
    print("客户端",addr)
    while True:
        try:
            cmd = conn.recv(BUFSIZE)
            if len(cmd) == 0:break
            #执行命令, 得到命令的运行结果cmd_res
            res= subprocess.Popen(cmd.decode("utf-8"),shell=True,
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
            err = res.stderr.read()
            if err:
                cmd_res = err
            else:
                cmd_res = res.stdout.read()
            len_1 = (len(cmd_res))
            conn.send(str(len_1).encode("utf-8"))
            conn.recv(BUFSIZE)
            conn.sendall(cmd_res)
        except Exception as e:
            print(e)
            break
    conn.close()
server
import socket,time
BUFSIZE=1024
ip_port=('127.0.0.1',1111)

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
res=s.connect_ex(ip_port)

while True:
    msg=input('>>: ').strip()
    if len(msg) == 0:continue
    if msg == 'quit':break
    s.send(msg.encode('utf-8'))
    comm = s.recv(BUFSIZE)
    comm = int(comm.decode("utf-8"))
    s.send("1".encode("utf-8"))
    start_size = 0
    while start_size < comm:
        act_res=s.recv(1024)
        print(act_res.decode('gbk'),end='')
        start_size += 1024
client

 

解决粘包

'''
1.先求报头长度,用struct取出来
2.根据取出的长度去报头内容, 然后解码, 反序列化
3.从反序列化的结果中取出数据的详细信息,然后去取真实的数据内容
'''
import socket,struct,json
import  subprocess
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
phone.bind(("127.0.0.1",8080))
phone.listen(5)

while True:
    conn,addr = phone.accept()
    while True:
        cmd = conn.recv(1024)
        if not cmd:break
        print("cmd: %s"%cmd)

        res = subprocess.Popen(cmd.decode('utf-8'),
                               shell = True,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        err = res.stderr.read()
        print(err)
        if err:
            back_msg = err
        else:
            back_msg=res.stdout.read()
        headers = {'data_size':len(back_msg)}
        head_json = json.dumps(headers)
        head_json_bytes = bytes(head_json,encoding='utf-8')
        conn.send(struct.pack('i',len(head_json_bytes)))  #报头的长度
        conn.send(head_json_bytes) #发送报头
        conn.sendall(back_msg)     #再发真实的内容
    conn.close()
server
from socket import *
import struct,json

ip_port=('127.0.0.1',8080)
client=socket(AF_INET,SOCK_STREAM)
client.connect(ip_port)

while True:
    cmd=input('>>: ')
    if not cmd:continue
    client.send(bytes(cmd,encoding='utf-8'))
    head = client.recv(4)
    head_json_len = struct.unpack('i',head)[0]
    head_json = json.loads(client.recv(head_json_len).decode("utf-8"))
    data_len = head_json['data_size']

    recv_size = 0
    recv_data = b''
    while recv_size < data_len:
        recv_data += client.recv(1024)
        recv_size += len(recv_data)
    print(recv_data.decode("gbk"))
client

 

posted on 2018-08-27 19:45  augustyang  阅读(221)  评论(0编辑  收藏  举报

导航