Socket server
#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5) whileTrue: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-*-ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.connect (ip_port) sendstr="What's 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 results
client:send> What's your name? Recv> My name is Tian nan server:server waiting...recv> What's your name? Send> I call Sky South Server Waiting ...
A simple Web server application
#!/usr/bin/Env Python#coding:utf-8Import Socket def handle_request (client): BUF= Client.recv (1024x768) Client.send ("http/1.1 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) whiletrue:connection, Address=sock.accept () handle_request (connection) connection.close ()if__name__ = ='__main__': Main ()
Visit http://localhost:8080
Python-socket Module