Receive our weekly advanced programming tips for FREE
17.April
Send binary data over socket with python
0
| 0 votes
Autor: bookkeeper
Chapter: Python
How do i send a number over socket? It's very easy with struct module!
from socket import *
import struct

#sent binary data over socket

try:
    #create socket
    s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)

    #connect to server
    s.connect( ("www.programmersbook.com", 80) )

    #pack data
    #http://docs.python.org/lib/module-struct.html

    packed_int = struct.pack("i", 1000) # i = int, I = unsigned int

    # send data
    s.send(packed_int)
    #read response
    print( s.recv(1024) )
except(error,timeout), e:
    print(e)
except Exception:
    print("unknown except(%s) :(" % e)