Client Socket Connection to Java server

MRAB google at mrabarnett.plus.com
Fri Jan 16 15:43:53 CET 2009


TechieInsights wrote:
> I am having problems with a socket connection to a Java server.  In
> java I just open the socket, pass the length and then pass the bits
> across the socket.
> 
> I created a socket object:
> 
> import socket
> 
> class MySocket:
> 	def __init__(self, host='localhost', port = 28192, buffsize = 1024):
> 		socket.setdefaulttimeout(10)
> 
> 		self.host = host
> 		self.port = port
> 		self.buffsize = buffsize
> 		self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> 		self.socket.connect((host, port))
> 
> 	def send(self, data):
> 		self.socket.send(data)

I recommend sendall() instead of send():

  		self.socket.sendall(data)

send() doesn't guarantee to send all the data, so multiple sends might 
be needed to send it all. sendall() does that for you.

> 
> 	def receive(self):
> 		return self.socket.recv(self.buffsize)
> 
> 	def sendAndReceive(self, data):
> 		self.send(data)
> 		return self.receive()
> 
> 	def close(self):
> 		self.socket.close()
> 
> But the java server gives the error:
> WARNING: <Incoming> Message length invalid.  Discarding
> 
> The data is of type string (xml).  Am I doing something wrong?  I know
> you have to reverse the bits when communicating from C++ to Java.
> Could this be the problem? I figured it would not because it said the
> length was invalid.  I just started looking at python sockets
> tonight... and I don't have a real deep base with socket connections
> as it is... any help would be greatly appreciated.
> 
> Greg
> --
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list