Case 1:
Service side:
#!/usr/bin/env python# encoding:utf-8 "" "@version:?? @author: Phpergao@license:apache Licence @file: socket_server.py@time:2016-05-22 19:22 "" "Import socketip_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 (1024x768) print (str (client_data,encoding= "Utf-8")) Conn.sendall (bytes ("Don't answer, I don't want to be occupied" , encoding= "Utf-8")) Conn.close ()
Client:
Import socketip_port= ("127.0.0.1", 9999) Sk=socket.socket () sk.connect (ip_port) sk.sendall (bytes ("Request to occupy the Earth", encoding= "Utf-8") Sk.sendall (bytes ("I'm going to start invading the Earth", encoding= "Utf-8")) Server_reply=sk.recv (1024x768) print (str (server_reply, encoding= "Utf-8")) Sk.close ()
Case 2:
Service side:
Import socketip_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 (1024x768) print (str (client_data,encoding= "Utf-8")) conn.sendall (Bytes ("Don't answer, I don't want to be occupied", encoding= "Utf-8")) while true: try:    CLIENT_DATA=CONN.RECV (1024x768) print (str (client_data,encoding= "Utf-8")) except exception: print ("client Close. ") break conn.send (Client_data) conn.close ()
Client:
Import socketip_port= ("127.0.0.1", 9999) Sk=socket.socket () sk.connect (ip_port) sk.sendall (bytes ("Request to occupy the Earth", encoding= "Utf-8") Sk.sendall (bytes ("I'm going to start invading the Earth", encoding= "Utf-8")) Server_reply=sk.recv (1024x768) print (str (server_reply, encoding= "Utf-8")) while True:enter=input ("Enter:") sk.send (bytes (enter,encoding= "Utf-8")) Sk.close ()
On the Linux service side:
import socketip_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 (1024x768) print (str (client_data,encoding= "Utf-8")) conn.sendall (Bytes ("Don't answer, I don't want to be occupied", encoding= "Utf-8")) while True:        CLIENT_DATA=CONN.RECV (1024x768) print (str (client_data,encoding= "Utf-8")) if not client_data: break conn.send (Client_data) conn.close ()
Python Socket Interactive Communication