python3.* socket例子

On Server:

# -*- 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(('localhost',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:
            conn.send('welcome client!')
        
        conn.close()
        print('end of the service')
        

On Client:

import socket

if "__main__" == __name__:


    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect(('localhost',8008))
    sock.send(b'0')
    
    szBuf = sock.recv(1024)
    byt = 'recv:' + szBuf.decode('gbk')
    print(byt)
    
    sock.close()
    print('end of the connecct')

原文地址:https://www.cnblogs.com/mrchige/p/6222714.html