Socket programming in Python
This is a quick guide/tutorial on socket programming in python. Socket programming python is very similar to C.
To summarise the basics, sockets are the fundamental "things" behind any kind of network communications done by your computer.
For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype.
Any network communication goes through a socket.
In this tutorial we shall be programming Tcp sockets in python. You can also program udp sockets in python.
Coding a simple socket client
First we shall learn how to code a simple socket client in python. A client connects to a remote host using sockets and sends and receives some data.
1. Creating a socket
This first thing to do is create a socket. The socket.socket
function does this.
Quick Example :
#Socket client example in python import socket #for sockets #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket Created'
Function socket.socket
creates a socket and returns a socket descriptor which can be used in other socket related functions
The above code will create a socket with the following properties ...
Address Family : AF_INET (this is IP version 4 or IPv4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Error handling
If any of the socket functions fail then python throws an exception called socket.error which must be caught.
#handling errors in python socket programs import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created'
Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
2. Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample.
First get the IP address of the remote host/url
Before connecting to a remote host, its ip address is needed. In python the getting the ip address is quite simple.
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip
Now that we have the ip address of the remote host/system, we can connect to ip on a certain 'port' using the connect function.
Quick example
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip
Run the program
$ python client.py Socket Created Ip address of www.google.com is 74.125.236.83 Socket Connected to www.google.com on ip 74.125.236.83
It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.
OK, so we are now connected. Lets do the next thing , sending some data to the remote server.
Free Tip
The concept of "connections" apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable "stream" of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by data from other pipes. Another important property of stream connections is that packets have an "order" or "sequence".
Other sockets like UDP , ICMP , ARP dont have a concept of "connection". These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
3. Sending Data
Function sendall
will simply send data.
Lets send some data to google.com
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip #Send some data to remote server message = "GET / HTTP/1.1\r\n\r\n" try : #Set the whole string s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully'
In the above example , we first connect to an ip address and then send the string message "GET / HTTP/1.1\r\n\r\n" to it. The message is actually an "http command" to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
4. Receiving Data
Function recv
is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
#Socket client example in python import socket #for sockets import sys #for exit #create an INET, STREAMing socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print 'Failed to create socket' sys.exit() print 'Socket Created' host = 'www.google.com'; port = 80; try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip #Send some data to remote server message = "GET / HTTP/1.1\r\n\r\n" try : #Set the whole string s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully' #Now receive data reply = s.recv(4096) print reply
Here is the output of the above code :
$ python client.py Socket Created Ip address of www.google.com is 74.125.236.81 Socket Connected to www.google.com on ip 74.125.236.81 Message send successfully HTTP/1.1 302 Found Location: http://www.google.co.in/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: PREF=ID=51f26964398d27b0:FF=0:TM=1343026094:LM=1343026094:S=pa0PqX9FCPvyhBHJ; expires=Wed, 23-Jul-2014 06:48:14 GMT; path=/; domain=.google.com
Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
5. Close socket
Function close
is used to close the socket.
s.close()
Thats it.
Lets Revise
So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply
Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.
The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
Now its time to do some server tasks using sockets.
Coding socket servers in Python
OK now onto server things. Servers basically do the following :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
1. Bind a socket
Function bind
can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Quick example
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete'
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.
2. Listen for incoming connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen
is used to put the socket in listening mode. Just add the following line after bind.
s.listen(10) print 'Socket now listening'
The parameter of the function listen is called backlog. It controls the number of incoming connections that are kept "waiting" if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.
Now comes the main part of accepting new connections.
3. Accept connection
Function socket_accept
is used for this.
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #wait to accept a connection - blocking call conn, addr = s.accept() #display client information print 'Connected with ' + addr[0] + ':' + str(addr[1])
Output
Run the program. It should show
$ python server.py Socket created Socket bind complete Socket now listening
So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
$ telnet localhost 8888
It will immediately show
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host.
And the server output will show
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:59954
So we can see that the client connected to the server. Try the above steps till you get it working perfect.
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Function sendall
can be used to send something to the socket of the incoming connection and the client should see it. Here is an example :
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) #now keep talking with the client data = conn.recv(1024) conn.sendall(data) conn.close() s.close()
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy happy Connection closed by foreign host.
So the client(telnet) received a reply from server.
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. After all its a server meant to serve.
So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept
in a loop so that it can receive incoming connections all the time.
4. Live Server - accepting multiple connections
So a live server will be alive always. Lets code this up
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 5000 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #now keep talking with the client while 1: #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) data = conn.recv(1024) reply = 'OK...' + data if not data: break conn.sendall(reply) conn.close() s.close()
We havent done a lot there. Just put the socket_accept in a loop.
Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
$ telnet localhost 5000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy OK .. happy Connection closed by foreign host.
And the server terminal would show
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:60225 Connected with 127.0.0.1:60237 Connected with 127.0.0.1:60239
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show "Connection closed by foreign host."
Good so far. But still the above code does not establish an effective communication channel between the server and the client.
The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time.
So now its time to handle the connections, and handle multiple connections together.
5. Handling Multiple Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads.
The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
We shall now use threads to create handlers for each connection the server accepts.
import socket import sys from thread import * HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' #Bind socket to local host and port try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' #Start listening on socket s.listen(10) print 'Socket now listening' #Function for handling connections. This will be used to create threads def clientthread(conn): #Sending message to connected client conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string #infinite loop so that function do not terminate and thread do not end. while True: #Receiving from client data = conn.recv(1024) reply = 'OK...' + data if not data: break conn.sendall(reply) #came out of loop conn.close() #now keep talking with the client while 1: #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. start_new_thread(clientthread ,(conn,)) s.close()
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome to the server. Type something and hit enter hi OK...hi asd OK...asd cv OK...cv
The server terminal might look like this
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:60730 Connected with 127.0.0.1:60731
The above connection handler takes some input from the client and replies back with the same.
So now we have a server thats communicative. Thats useful now.
Conclusion
By now you must have learned the basics of socket programming in python. You can try out some experiments like writing a chat client or something similar.
When testing the code you might face this error
Bind failed. Error Code : 98 Message Address already in use
When it comes up, simply change the port number and the server would run fine.
If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.
great
Awesome tutorial :)
Hi
This is very useful to me.Thanks.
Thank you so much! I enjoyed reading it, as it was very simple and informative…The internet needs more things like this :)
Thanks so much for this! This helps a great deal with a hardware/software project I just started. You’ve saved me a _lot_ of time and I really appreciate it!
Really useful! I came here without understanding a word of the networking jargon (except ‘IP address’). I still don’t, but I still managed to get all my devices communicating perfectly and exactly how I wanted :P
Simple, neat and bull’s eye tutorial :)
Thanks a lot…
awesome, thank you!
This! Exactly what I’ve been looking for a while, and finally I found it :D If it onla was in 3.x too, but with google I could find everything after awhile :)
You ARE the Man!!!! This rocked! Thank you for all the time you put into it.
Thanks a lot…good in socket communication!!!!
Hello, Im having some small problems when using this, I keep getting syntax errors, even if I copy and paste, I’ve tried using both Python 2.7 and 3.3.3. But the print function seems to have a fit saying Invalid Syntax, or it has a fit when typing , into any part of the code. Any help would be appreciated:)
If using Python 3.3.3 on the server script, you need to send the data in binary form instead of a string.
conn.send(‘Welcome to the server. Type something and hit entern’)
should look like this:
conn.send(b’Welcome to the server. Type something and hit entern’)
The same goes for the reply = ‘OK…..’ + data. It should be:
reply = (b’OK….’ + data)
You’ll also need to import _thread instead of thread like this:
from _thread import *
You’ll also need to change the except section from
except socket.error, msg:
to look like this:
except socket.error as msg:
Thanks mate!!
Very good,informative and clear article.
BR,
Ariel.
Perfect! Thank you a lot!
very well written. Start writing books!
Why did this have to end. I enjoyed every minute of this..
thank you very much for your tutorial!
Thank you for this article. It provides a clear introduction to socket programming without assuming you know a hundred other modules first. By far, the best tutorial I’ve ever read on Python socket programming.
Great tutorial, learned a ton from this! One question, every time I connect with the server, the port increments by 1. For example, in your server terminal output screen, you have
Connected with 127.0.0.1:60730
Connected with 127.0.0.1:60731
The next time, it would be:
Connected with 127.0.0.1:60732
Then:
Connected with 127.0.0.1:60733
and so on… Is this an issue? Shouldn’t it always be connecting to the same port? What happens when it runs out of ports?
Thanks!
those big port numbers are the client side port numbers and they do increase like that with every connection. If it runs out of port numbers on the higher side, it will look for a port number again from the beginning.
OK Thanks!
So as long as the socket is closed using s.close(), when the ports wrap around to the beginning again, it can be re-used?
Hi, thanks for the clear and concise tutorial. I have had the following output in my telnet.. i’m using putty in passive mode like you suggested to someone else, as I’m on windows 7.
My output is: hi there
Ok….hi thereOk….
The extra ‘Ok….’ is confusing to me, I can’t figure out why it’s happening. I thought it might have something to do with pressing ‘Enter’ after typing the message but I can’t see a way around that. I am relatively new to Python. Cheers.
Change your Putty settings, currently it uses the Windows default line ending of and your server sees this as two messages, one message is blank. Change Putty to only add and your server code will work as designed.
Thank you. We need people like you in the open community.
No crap, no shit – Clear, concise, covers everything and to the point.
Thanks again!
good job man!
I am searching for the socket programming tutor from a long time,
Its one of the best tutor i found in google
keep it up
One suggestion:
Please add threading concepts too
If possible add some extra resources for the reference
for ex: If possible attach the link to download the chat program
really nice work
really a nice tutorial :) I enjoyed reading it…..simple and to the point.
http://freepythontips.wordpress.com/
While executing the code given under “Live Server” heading, I get the following error.
Socket Created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:49913
Traceback (most recent call last):
File “server.py”, line 28, in
reply = ‘OK…’ + data
TypeError: Can’t convert ‘bytes’ object to str implicitly
I am using Python 3.3.2 on Windows.
You will have to cast the variable data into a string.
Check if this will work:
reply = ‘OK…’ + str(data)
use python 2.7.2, its also stable
It is awesome !!
Man, this article is simple, linear and neat! I learned more here in 10 mins than a tons of other similar articles. thanks
nobody cares
Nice article.
Thanks man I learnt from you :)
Will this work between computers on separate networks if you use an external IP? Will ports have to be manually opened on routers?
yes, socket programs work across any network given that the ip address + ports are accessible.
yes ports have to be opened on routers with port forwarding.
What a phenomenal tutorial! Incredibly well written and fun to code along with. Thanks!
Hi, Great article! I’m fairly new to python and found this extremely useful and informative. I seem to have a problem when running the server code however. Every time I enter a key stroke, for example the letter ‘a’, it immediately responds with “Ok….a”. So if i were to try and write ‘apple’ it would look like this: “aOk…a pOk…p pOk…p lOk….l eOk…e”.
I know this has something to do with what triggers the response in the “Send message to connected client” while loop, but i’m not sure how to only send a response when the user hits enter in the telnet terminal. Any suggestions on how to fix that?
Thanks
this is a problem with the telnet client on windows. on windows the telnet client is in “character mode” by default, which means that it will transmit every single character the moment it is typed.
To fix the issue, the following telnet clients can be used
1. ncat – it comes with nmap. syntax is same as telnet and works in line mode by default.
2. putty – putty will be in line mode when the “telnet negotiation mode” is set to passive.
I changed the settings for telnet in putty, and it works well. Thanks!
Hi, it would also be good if you mentioned in the post that this is about low-level socket API usage and you should rather program using eg Twisted rather than using the low-level API.
Awesome and informative. Thanks a ton.
This tutorial was very helpful and informative. It gave a fairly clear view of how blocking sockets in Python works. It could have included some information about the nature of blocking sockets though (what does it mean that the socket is blocking), and perhaps a section on how to make non-blocking sockets.
thanks for the suggestion. will soon write a tutorial on non-blocking sockets in python.
Thanks a lot
Hi quite new to python programming anyhow I am basically running the server code from this tutorial on my raspberry pi and your coding tells me that the server is binded and listening. But when I go on my netbook and do the Telnet command in a terminal it refuses the connection.
Any help would be greatly appreciated. My netbook is running on Linux Mint and the Raspberry Pi is running Raspbian a version of Linux. Both are connected to my router the Pi via an ethernet cable and the netbook wirelessly.
is your netbook able to ping raspberry pi ?
if yes, then is the raspberry pi running any firewall ? firewalls might block incoming connections.
Hi Silver Moon I think I have your code working I was literally typing in ‘Telnet localhost 8888’ and instead I typed ‘Telnet 192.168.1.69 8888’ and it worked straight away. The 192.168.1.69 being the address of my Raspberry Pi. Will carry on working through your code as I want to try and code a simple Chat client over my home network. Thanx.
Hey, could you please include information regarding how to swap this from a socket working on the local machine to one that acts across the LAN between two computers? cheers
check out the server example on the 2nd page
https://www.binarytides.com/python-socket-programming-tutorial/2/
run the server program on one machine (say its ip is 192.168.1.50)
then run the client program on another machine and give it the above ip address to connect.
cheers m8, that worked great. Slightly embarrassed I didn’t figure that out for myself.
very nice description
Excellent explanation, this was very helpful thanks alot
Thank’s for the tutorial. Easy to learn
Thank you brave Silver Moon. Thanks to your open post the Python Language got another dimension to me. Have a great time. Bye
Great post. Thanks so much, it works well!
This is a very well explained tutorial, containing much that you often don’t get by reading documentation. Many thanks.
sopier: It’s because the request is missing the “Host” header. HTTP/1.1 requires you to send “Host: ” in the second line, i.e. “GET / HTTP/1.1\r\nHost: http://www.google.com\r\n\r\n”
Its to keep things simple in the beginning.
Very useful tips, well explained for beginner as well as intermediate level Python Programmers.
For more such tips and tutorials, please visit Python Central, a strong opensource community for Python enthusiast.
Thank you very much for this tutorial, I love python and want to use it to build a real time web application but I’m not sure where to start, I was told to start with socket programming and I’ve found this the most useful tutorial after over a month of search for a good tutorial, thanks again! I’ll be sure to recommend this :)
That said though, I want to ask, in my quest to build a real time web app, what should be my next step?
The last code has some glitch on windows… when a client types a message, it immediately followed by ‘Ok…%message’ %(message)s.
so for example if i want to type “hello”, the very moment i type “h”, it is followed by “Ok…h” and I’m not allowed to type the whole phrase and hit enter first… how do i fix this?
what kind of realtime application are you trying to build ?
If you want to make a web application then you probably dont need sockets.
web applications work inside the browser so you need to use ajax and server side scripting.
yes a real time web application is what I want to build, but wouldn’t I need sockets to be able to understand the Twisted framework which I heard Orbited is built upon and in combination with django I could build a real time web app? I’m still new to all this :/
Twisted framework is a library that can be used to build socket/client applications like servers and clients quickly.
So yes, having knowledge of basic socket programming and protocols is necessary to work with it.
Apart from that you can also look into the websockets api of html5 that allows browsers to make realtime socket like
communication from javascript.
I’m using HTTP/1.1 and the result is bad request, I switch to 1.0 and it doin fine.. Also some of your code still contain semicolon on the end of the line like (host = ‘www.google.com’; port = 80;) I thought Python doesn’t need that :) Anyway still good reading.. Thanks..
About the error message, that’s because, when you are using TCP, you may be in a state where the algorithm waits for all the sockets to close (TIME_WAIT state). It may take up to 2 minutes, which is really bothersome, especially when you debug/develop.
To suppress the waiting and allow the socket port to be reused at once (instead of changing the port in your code), just add this setting just before your bind sentence:
setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Very Usefull..Thanx a ton for the tutorial…:)