>>\') if info == \'q\': coon.send(b\' ...' />

python socket黏包解决

#服务端
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 8080))
sk.listen()
coon, sddr = sk.accept()
while True:
    info = input('>>>')
    if info == 'q':
        coon.send(b'q')
        break
    coon.send(info.encode('gbk'))
    num = int(coon.recv(1024).decode('gbk'))
    coon.send(b'ok')
    msg = coon.recv(num).decode('gbk')
    print(msg)
sk.close()</code>
#客户端
<code>
import socket
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1', 8080))
while True:
    cmd = sk.recv(1024).decode('gbk')
    if cmd == 'q':
        break
    msg = subprocess.Popen(cmd,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    std_out = msg.stdout.read()
    std_err = msg.stderr.read()
    sk.send(str(len(std_out) + len(std_err)).encode('gbk'))
    sk.recv(1024)
    sk.send(std_out)
    sk.send(std_err)
sk.close()
北关漫步

北关漫步

咸鱼....

留下你的评论

*评论支持代码高亮<pre class="prettyprint linenums">代码</pre>