设为首页 加入收藏

TOP

Day9 网络编程(三)
2017-09-30 17:33:11 】 浏览:10971
Tags:Day9 网络编程
startswith('Start'):
conn.send(send_data) #发送命令执行结果
except Exception:
break
#挂电话
conn.close()
socket_client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import socket
ip_port = ('127.0.0.1', 9999)
#买手机
sk = socket.socket()
#拨号
sk.connect(ip_port) #连接服务端,若服务端有一个已经存在的链接,则连接挂起
#发消息
while True: #基于connect建立的链接来循环发送消息
send_data = input(">>>: ").strip()
if len(send_data) == 0:continue
sk.send(bytes(send_data, encoding='utf8'))
if send_data == 'exit':break

#解决粘包问题
#接收消息,其实是为了得到‘Ready|内容长度’
ready_tag = sk.recv(1024)
ready_tag = str(ready_tag, encoding='utf8')
#收到‘Ready|内容长度’
if ready_tag.startswith("Ready"):
#获取待接收数据的长度
msg_size = int(ready_tag.split('|')[-1])
#准备一个‘Start’
start_tag = 'Start'
#发送一个‘Start’消息,通知服务端可以发送消息了
sk.send(bytes(start_tag, encoding='utf8'))

recv_size = 0
recv_msg = b''
while recv_size < msg_size:
recv_data = sk.recv(1024)
recv_msg += recv_data
recv_size += len(recv_data)
print('MSG SIZE %s RECV SIZE %s' % (msg_size, recv_size))
print(str(recv_msg, encoding='utf8'))
#挂电话
sk.close()

socketserver解决粘包问题

import socketserver
import subprocess

class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            conn=self.request
            conn.sendall(bytes("欢迎登录","utf8"))
            while True:
                client_bytes=conn.recv(1024)
                if not client_bytes:break
                client_str=str(client_bytes,"utf8")
                print(client_str)
                command=client_str

                result_str=subprocess.getoutput(command)
                result_bytes = bytes(result_str,encoding='utf8')
                info_str="info|%d"%len(result_bytes)
                conn.sendall(bytes(info_str,"utf8"))
                # conn.recv(1024)
                conn.sendall(result_bytes)
            conn.close()

if __name__=="__main__":
    server=socketserver.ThreadingTCPServer(("127.0.0.1",9998),Myserver)
  &nb

首页 上一页 1 2 3 4 5 下一页 尾页 3/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python面试题 —— 计算列表中出.. 下一篇利用Python进行数据分析(6) NumPy..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目