SocketServer and a Java applet listener

Steve Horsley steve.horsley at gmail.com
Sat Aug 27 19:33:33 CEST 2005


google at phaedro.com wrote:
> Dear newsgroup,
> 
> I give up, I must be overseeing something terribly trivial, but I can't
> get a simple (Java) applet to react to incoming (python) SocketServer
> messages.
> 
> Without boring you with the details of my code (on request available,
> though), here is what I do :
> 
> I have a TCPServer and BaseRequestHandler .
> Connecting via telnet : everything goes OK.
> 
> Connecting from Applet :
> problem 1 (worked around it) : java has some 'propietary' UTF-8 format,
> python's unicode doesn't seem to handle it correctly and I have to
> strip the first two bytes/chars , then all goes OK .
> 

Those 2 bytes are important! They are a string length indicator. 
Here are the docs that tell you that it puts a 2-byte length on 
the front:
http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.html#writeUTF(java.lang.String)
If you are ignoring these bytes, then how can you be sure you 
have received the whole string? Please don't tell me you "just 
hope" that the whole string will always arrive in a single read() 
call. There is no guarantee of that. TCP does NOT have message 
boundaries, and TCP packets can be both fragmented and coalesced.
E.g. if you do:
     out.write('Steve was here")
     out.flush()
     out.write("Bilbo Baggins wasn't")
     out.flush()

it is entirely legal for two successive read() calls to retrieve 
"steve was " and "hereBilbo Baggins wasn't". Although in 
practice, fragmentation won't normally happen until strings reach 
  around 1500 bytes.

writeUTF tries to fix the problem by telling the receive how much 
string to expect.


> problem 2:
> I have tried IMHO everything.
> In the BaseRequestHandler.handle() method, I want to update a list of
> clients in the server, i.e.:
> 
> self.server.players[username] = self
> 
> self := instance of the BaseRequestHandler, I only do this after
> succesfull connect , i.e. first time socket. I assume (wrongfully?)
> that I can now use the self.request socket for future transmissions to
> the client.
> 
> In the applet, I start a thread that listens to the socket by eternally
> looping over:
> String line = self.din.readUTF()
> if (line == null)
>     break;
> handle(line);
> 

Probably the same problem. If you didn't send a 2 byte length 
indicator first, then java's readUTF() will have tried to 
interpret the first 2 bytes that you did actually send as the 
string length, and may well simply be waiting patiently for the 
rest to arrive.

HTH
Steve



More information about the Python-list mailing list