title: howto program protocol buffer in python to send messages via socket
body: <p>I'm trying to use protocol buffer in python to send a message from one to another computer.  I learned from a few online examples, and tried to make a minimum example out of them.  However, in my code, the server does not print out the correct values of the variables the client sends.  Any help is very much appreciated.</p>
  
  <p>First, test_msg.proto is as follows:</p>
  
  <pre><code>message test_msg {
      required int32 param1 = 1;
      required int32 param2 = 2;
  }
  </code></pre>
  
  <p>Second, client code (test_client.py)</p>
  
  <pre><code>from test_msg_pb2 import test_msg
  import socket
  import sys
  import struct
  
  address = ('localhost', 6005)
  client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  client_socket.connect(address)
  data = test_msg()
  
  num_retransmits = 0
  while(num_retransmits &lt; 10): # send the same message 10 times
      num_retransmits = num_retransmits + 1
  
      data.param1 = 100
      data.param2 = 5
      s = data.SerializeToString()
  
      totallen = 4 + len(s) 
      pack1 = struct.pack('&gt;I', totallen) # the first part of the message is length
      client_socket.sendall(pack1 + s)
  
      print "[client] param1: ", data.param1, " param2: ", data.param2
  </code></pre>
  
  <p>Third, the server code (test_server.py)</p>
  
  <pre><code>from test_msg_pb2 import test_msg
  import socket
  import sys
  import struct
  
  address = ('localhost', 6005)
  server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  server_socket.bind(address)
  
  while(1):
      print "Listening"
  
      totallen = server_socket.recv(4)
      totallenRecv = struct.unpack('&gt;I', totallen)[0]
      messagelen = totallenRecv - 4 
      message = server_socket.recv(messagelen)
  
      msg = test_msg()
      msg.ParseFromString(message)
  
      print "[server] param1:", msg.param1, "param2:", msg.param2
  </code></pre>
  
  <p>Then, after starting the server, I executing the client and it print out the following 10 lines as it send the param 10 times</p>
  
  <pre><code>[client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  [client] param1: 100 param2: 5
  </code></pre>
  
  <p>However, on the server side, it prints out</p>
  
  <pre><code>Listening
  [server] param1: 0 param2: 0
  Listening
  [server] param1: 0 param2: 0
  Listening
  [server] param1: 0 param2: 0
  Listening
  [server] param1: 0 param2: 0
  Listening
  [server] param1: 0 param2: 0
  Listening
  </code></pre>
  
  <p>So, the unpacked number param1 and param2 are incorrect, and it received the message only half of the times.  Thanks so much for your help.</p>