Python-socket module, pythonsocket
Socket server
#! /Usr/bin/env python #-*-coding: UTF-8-*-import socketip_port = ('2017. 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 = "My name is Tian Nan" conn. sendall (resp. encode ('utf-8') print ("send>", resp) conn. close ()
Socket client
#! /Usr/bin/env python #-*-coding: UTF-8-*-import socketip_port = ('2017. 0.0.1 ', 9999) sk = socket. socket () sk. connect (ip_port) sendstr = "What is your name? "Sk. sendall (sendstr. encode ('utf-8') print ("send>", sendstr) server_reply = sk. recv (1024) print ("recv>", server_reply.decode ('utf-8') sk. close ()
Execution result
Client: send> what is your name? Recv> my name is tiannan server: server waiting... recv> what is your name? Send> my name is tiannan server waiting...
A simple web server application
#!/usr/bin/env python#coding:utf-8import 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()
Access http: // localhost: 8080