zoukankan      html  css  js  c++  java
  • socket 简历网络连接

    # server 代码

    import socket
    import threading
    import time
    # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # s.connect(('www.sina.com.cn',80))
    # s.send(b'GET / HTTP/1.1 Host: www.sina.com.cn Connection: close ')
    #
    # buffer = []
    # while True:
    # d = s.recv(1024)
    # if d:
    # buffer.append(d)
    # else:
    # break
    #
    # data = b''.join(buffer)
    # s.close()
    #
    # header, html = data.split(b' ', 1)
    # print(header.decode('utf-8'))
    #
    # with open('sina.html', 'wb') as f:
    # f.write(html)


    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1',9999))
    s.listen(5)
    print('Waiting for connection...')


    def tcplink(sock, addr):
    print('Accept new connection from %s:%s...'%addr)
    sock.send(b'Welcome!')
    while True:
    data = sock.recv(1024)
    time.sleep(1)
    if not data or data.decode('utf-8') == 'exit':
    break
    sock.send(('Hello, %s!'%data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)


    while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()

    # client 代码

    import socket

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 9999))
    print(s.recv(1024).decode('utf-8'))
    for data in [b'liu', b'hong', b'tao']:
    s.send(data)
    print(s.recv(1024).decode('utf-8'))

    s.send(b'exit')
    s.close()
  • 相关阅读:
    kindle--瓦尔登湖
    8051
    c++
    Linux安装目录的选择
    Redis键值数据类型之散列类型
    Redis键值数据类型之字符串
    redis基本使用
    Ubuntu18.04 Redis安装
    Java String和int转换
    mysql获得自增主码的值
  • 原文地址:https://www.cnblogs.com/LewisAAA/p/9249848.html
Copyright © 2011-2022 走看看