python socket

作者: bianruifeng | 来源:发表于2020-04-07 21:23 被阅读0次

启动服务:

# -*- coding: utf-8 -*-
#this is the server 
import socket

if "__main__" == __name__:
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print("create socket suc!")
        
        sock.bind(('192.168.43.51', 8008))
        print('bind socket suc!')
 
        sock.listen(5)
        print('listen socket suc!')      
        
    except:
        print("init socket err!")
        
    while True:
        print('listren for client...')
        conn,addr = sock.accept()
        print('get client')
        print(addr)
        
        conn.settimeout(5)
        szBuf = conn.recv(1024)
        byt = 'recv:' + szBuf.decode('gbk')
        print(byt)
        
        if '0' == szBuf:
            conn.send('exit')
        else:

            str = 'welcome client!'.encode()
            conn.send(str)
        
        conn.close()
        print('end of the service')
        

启动客户端:

import socket

if "__main__" == __name__:
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创建
    sock.connect(('192.168.43.51',8008))#连接
    sock.send(b'0')#发送消息到服务器
    #获得服务器返回消息输出
    szBuf = sock.recv(1024)
    byt = 'recv:' + szBuf.decode('gbk')
    print(byt)
    #断开连接
    sock.close()
    print('end of the connecct')

服务端输出:



客户端输出:


相关文章

网友评论

    本文标题:python socket

    本文链接:https://www.haomeiwen.com/subject/itvophtx.html