python-socket模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\\r\\n\\r\\n".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

技术分享

 

以上是关于python-socket模块的主要内容,如果未能解决你的问题,请参考以下文章

python-socket编程简例

Python-socket网络编程-Day8

python-socket和进程线程协程(代码展示)

python-socket

python-socket2

攻克python-socket