python3 socket实现

来源:互联网 发布:linux操作系统下载官网 编辑:程序博客网 时间:2024/06/07 03:45

1.服务端:

import socketdef listen():    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)    s.bind(('localhost', 8888))    s.listen(5)    while True:        connection, address = s.accept()        print('connection:::', connection)        print('address:::', address)        try:            connection.settimeout(5)            buf = connection.recv(1024)            print('buf::', buf)            if buf == '1':                connection.send(str.encode('welcome to server!'))            else:                connection.send(str.encode('please go away.'))        except socket.timeout:            print('time out')        connection.close()if __name__ == '__main__':    print('begin...')    listen()    print('end...')

2.客户端:

import socketdef client_connect():    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)    s.connect(('localhost', 8888))    import time    time.sleep(2)    s.send(str.encode('test'))    print('1', s.recv(1024))    s.close()if __name__ == '__main__':    client_connect()