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()
  • 相关阅读:
    php的session和cookie
    CRUD
    hibernate关系映射
    hibernate hql
    String和StringBuffer的区别
    策略模式Strategy
    项目结构
    final关键字
    项目中的建议
    struts学习记录
  • 原文地址:https://www.cnblogs.com/LewisAAA/p/9249848.html
Copyright © 2011-2022 走看看