Sending data via TCP
suggest changeSending data over the internet is made possible using multiple modules. The sockets module provides low-level access to the underlying Operating System operations responsible for sending or receiving data from other computers or processes.
The following code sends the byte string b'Hello' to a TCP server listening on port 6667 on the host localhost and closes the connection when finished:
from socket import socket, AF_INET, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
s.connect(('localhost', 6667)) # The address of the TCP server listening
s.send(b'Hello')
s.close()
Socket operations are blocking by default, so the program waits in the connect and send calls until the action is completed. For connect, that means the server actually accepting the connection. For send, it only means that the operating system has enough buffer space to queue the data to be sent later. send may accept fewer bytes than given and returns that count.
Sockets should always be closed after use.