首页 > 代码库 > python-socket模块
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模块
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。