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