First, what is a socket?
Python official about Socket function See http://docs.python.org/library/socket.html
Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.
Sockets originate from UNIX, and one of Unix/linux's basic philosophies is "Everything is File", which is used to open, read, write, and close the file. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)
The file module is opened, read-write, and closed for a specified
The socket module is open, read-write, and shut down for the server and client sockets
Second, give an example
1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 #Author:taoke4 ImportSocket5 ImportSYS6 Try:7 #Create socket8s =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)9 exceptSocket.error:Ten #creation failure, resulting in Socket.error exception One Print("Socket creat Error:"+str (socket.error)) A sys.exit () - - Print("creat Socket") theHost ='www.oschina.net' - - Try: - #Get host IP +REMOTE_IP =Socket.gethostbyname (host) - exceptSocket.gaierror: + Print("hostname could not being resolved,exiting") A sys.exit () at Print("IP Address of"+host+" is"+remote_ip) -Port = 80 - #Connection - S.connect ((remote_ip,port)) - Print('Socket Connected to'+ Host +'On IP'+remote_ip) - #Send Some data to remote server inMessage ="get/http/1.1\r\nhost:oschina.net\r\n\r\n" - to Try : + #Set the whole string - S.sendall (Message.encode ()) the exceptSocket.error: * #Send failed $ Print('Send failed')Panax Notoginseng sys.exit () - the Print('Message Send successfully') + A #Now receive data theReply = S.recv (4096) + - Print(Reply.decode ()) $ #Close Socket $S.close ()
The results of the operation are as follows:
creat socketip Address of Www.oschina.net is139.199.91.153Socket Connected to www.oschina.net on IP139.199.91.153Message Send Successfullyhttp/1.1 301Moved Permanentlyx-proxy:dayu-proxydate:wed,Sep 2017 13:28:07gmtcontent-type:text/htmlcontent-length:278X-dayu-UUID:D7PRC9C6CFCF6932495F893F61E66ABDB60CConnection:keep-Aliveset-cookie:__dayu_pp=733NA7YMM7VYJ7VBEQZ3FFFFFFFFEF192CB9EF6A; expires=wed, June 2021 23:59:59 GMT; path=/location:http:www.oschina.net/<! DOCTYPE HTML Public"-//ietf//dtd HTML 2.0//en">" White">TCP Client:
1 creating sockets, connecting remote addresses
# Socket.socket (Socket.af_inet,socket. SOCK_STREAM), S.connect ()
2 Send data and receive data after connection
# S.sendall (), S.RECV ()
3 When the transfer is complete, close the socket
#s. Close ()
Python socket programming