zoukankan      html  css  js  c++  java
  • python-socket模块

    socket server

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import socket
    
    ip_port = ('127.0.0.1',9999)
    
    sk = socket.socket()
    sk.bind(ip_port)
    sk.listen(5)
    
    while True:
        print('server waiting...')
        conn,addr = sk.accept()
    
        client_data = conn.recv(1024)
        print("recv>",client_data.decode('utf-8'))
    
        resp = "我叫天南"
        conn.sendall(resp.encode('utf-8'))
        print("send>",resp)
    
        conn.close()

    socket client

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import socket
    ip_port = ('127.0.0.1',9999)
    
    sk = socket.socket()
    sk.connect(ip_port)
    
    sendstr = "你叫什么名字?"
    sk.sendall(sendstr.encode('utf-8'))
    print("send>",sendstr)
    
    server_reply = sk.recv(1024)
    print("recv>",server_reply.decode('utf-8'))
    
    sk.close()

    执行结果

    client:
    send> 你叫什么名字?
    recv> 我叫天南
    
    server:
    server waiting...
    recv> 你叫什么名字?
    send> 我叫天南
    server waiting...

    一个简单的web服务器应用

    #!/usr/bin/env python
    #coding:utf-8
    import socket
     
    def handle_request(client):
        buf = client.recv(1024)
        client.send("HTTP/1.1 200 OK
    
    ".encode('utf-8'))
        client.send("Hello, World".encode('utf-8'))
     
    def main():
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('localhost',8080))
        sock.listen(5)
     
        while True:
            connection, address = sock.accept()
            handle_request(connection)
            connection.close()
     
    if __name__ == '__main__':
      main()

    访问http://localhost:8080

  • 相关阅读:
    16. Vue 登录存储
    JS 10位、13位时间戳转日期
    14.Vue 定义全局函数
    13.Vue+Element UI实现复制内容
    12.Vue+Element UI 获取input的值
    11.Vue安装Axios及使用
    Layui入手
    MongoDB自启动设置
    sql数据统计
    sql查询总结
  • 原文地址:https://www.cnblogs.com/tiannan/p/6214336.html
Copyright © 2011-2022 走看看