I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?
-
Python's socket module should be helpful. – owenmarshall Sep 16 '08 at 2:07
Opening sockets in python is pretty simple. You really just need something like this:
import socket
sock = socket.socket()
sock.connect((address, port))
and then you can send()
and recv()
like any other socket
OK, this code worked
s = socket.socket()
s.connect((ip,port))
s.send("my request\r")
print s.recv(256)
s.close()
It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.
-
For future reference, it's typically sound practice to used a larger parameter for socket.recv() than 256 bytes. I've frequently seen 4096 used. – junkforce Sep 16 '08 at 3:18
-
Yes, good idea junkforce. What I was really after was to read a line of text, I'm now using the makefile() function to buffer the received data which works a treat. – Adam Pierce Sep 17 '08 at 4:33
-
4
-
1for future readers: better to use
s.sendall
(os per @Jean-PaulCalderone comment) – wim Jan 29 '13 at 1:56
For developing portable network programs of any sort in Python, Twisted is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs.
-
2