Lesson 02
Socket Calls
Create a Python socket and use bind, listen, accept, connect, send, and recv to move one short text message between two programs.
Create a Python socket and use bind, listen, accept, connect, send, and recv to move one short text message between two programs.
Example
import socket
message = "Avery"
payload = message.encode()
print(payload)
print(payload.decode())
print(("127.0.0.1", 5050))
try:
probe = socket.socket()
probe.close()
print("socket closed")
except OSError:
print("This browser cannot open a socket.")encode() turns Avery into bytes, and decode() turns those bytes back into text. The address is the tuple ("127.0.0.1", 5050). socket() creates the object, and close() releases it. bind and listen belong to the server. connect belongs to the client. accept returns two values: the client connection, and an address pair of IP and port. send transmits bytes. recv(1024) reads up to 1024 bytes. A short message in this lesson fits in one read. The playground tries socket() and close(). If this browser refuses that object, the bytes and the address tuple still print. Later playgrounds do not call accept or connect, because those calls would wait.
Key takeaways
-
The module name is
socket -
socket()creates the object, andclose()releases it -
bind((host, port))andlisten(1)prepare the server -
connect((host, port))is the client reaching that server -
encode()makes bytes forsend, anddecode()makes text fromrecv -
Next: Server Program — accept one client and send one reply
-
Previous: Network Overview
Loading playground…
Check your understanding
Socket Calls Quiz
Which module holds socket, bind, and connect?
1 / 10