Communication between two machines via a network is done with special structures labeled socket. They designate points of entry / exit to the network, connected to an IP address and port number. We can distinguish two types of socket is: clients and servers. A client can only receive and transmit information while a server has additional powers. Among these, is the ability to wait for the connection of one or more clients. In Python sockets modules take place in the "socket" and "SocketServer". Built in the heart of these modules, Python API network proves to be a simple port system calls and libraries Unix in a form more suited to object-oriented programming. However, the functions have the same names as their equivalents C.
The sockets are distinguished according to two characteristics, their families and their type. The first of these may correspond to three values ??AF_UNIX, AF_INET and AF_INET6. As part of development oriented Internet, only the last two hold our attention. Family AF_INET sockets means based on the IPv4 AF_INET6 means while those based on IPv6. Thus, Python can be an ideal language to experience the new version of IP.
Discussion
The two socket types supported are also chosen between: SOCK_STREAM and SOCK_DGRAM. The first type is used to manipulate data streams and the second datagram. Finally, whatever the combination of family / type defined, note that a significant number of options apply to sockets and allow finer control of communications.
Create A Client Socket
Creating a socket to the calling code returns an object corresponding to the channel. To do this, it is necessary to invoke the method socket () this way:
from socket import * sock = socket (AF_INET, SOCK_STREAM)
The first parameter indicates the socket family and the second type. An optional third parameter can be specified, it corresponds to the protocol to use. The module defines several network such as IPPROTO_ICMP or IPPROTO_UDP. In most cases, this protocol number is zero (IPPROTO_IP) or the default. When in doubt, do not fill in this argument.
Once the socket is created, it should connect to a server, in the case of a client, or to bind to an address in the event of a server. The connection is thus:
sock. connect (('localhost', 2000))
We represent a connection address with a tuple containing the address of the server, either by its host name (eg 'irc.helix.org') or by its IP address (IPv4 here ' 127.0.0.1 '). When the connection can be established, the interpreter throws an exception of type socket.error.
Thereafter, send and receive data is really simple. For this, two methods will retain our attention: send () and recv (). The program must deal with a string. In response, we get the number of bytes actually issued. When network traffic is too much, it may be that all the bytes of the string is not issued, the application must be considered. However, we can force the issue of data integrity by running Sendall () ...