Socket programming starts by importing a socket library and creating a simple socket.
import socket s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed two parameters to it. The first parameter — AF_INET, and the second — SOCK_STREAM . AF_INET belongs to the ipv4 address family. SOCK_STREAM stands for connection oriented TCP.
We can now connect to the server using this socket.
Connecting to the server:
Please Note that if any error occurs during socket creation, socket.error is thrown and we can connect to the server only knowing that it is ip. You can find the IP address of the server using this:
$ ping www.google.com
You can also find the IP using Python:
import socket ip = socket.gethostbyname ('www.google.com') print ip
Here is an example script to connect to Google
< code class = "undefined spaces">
Now we need something the server can communicate with. We could send a request to the server to find out that our server is running. Enter these commands in a terminal:
# start the server $ python server.py
# keep the above terminal open
# Now open another terminal and type:
$ telnet localhost 12345
# in the server.py terminal you will see # this output: Socket successfully created socket binded to 12345 socket is listening Got connection from ('127.0.0.1', 52617)
# In the telnet terminal you will get this: Trying :: 1 ... Trying 127.0.0.1 ... Connected to localhost ... Escape character is '^]'. Thank you for connectingConnection closed by foreign host.
This output shows that our server is running.
Now for the client side:
# Import a socket module
# Create socket object
# Define the port you want to connect to
# connect to server on local computer
# receive data from the server
# close connection
# start the server: $ python server.py Socket successfully created socket binded to 12345 socket is listening Got connection from ('127.0.0.1', 52617)
# start the client: $ python client.py Thank you for c onnecting
Link: Python Socket Programming p>
This article courtesy of Kishlai Verma . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please write in comments if you find anything wrong or if you'd like to share more information on the topic discussed above.