Jython socket typecasting problems

Kent Johnson kent at kentsjohnson.com
Sun Feb 12 08:52:18 EST 2006


Mark Fink wrote:
> The cast to Integer for the port does not work either:
> 
> D:\AUT_TEST\workspace\JyFIT>jython fit/JyFitServer2.py "" 1234 23
> ['fit/JyFitServer2.py', '', '1234', '23']
> 
> Traceback (innermost last):
>   File "fit/JyFitServer2.py", line 146, in ?
>   File "fit/JyFitServer2.py", line 31, in run
>   File "fit/JyFitServer2.py", line 96, in establishConnection
>   File "D:\AUT_TEST\Jython21\Lib\socket.py", line 135, in connect
> TypeError: java.net.Socket(): 2nd arg can't be coerced to int
> 
> This is the code section of my server class (I cut this from a Python
> example):
>     def establishConnection(self):
>         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         self.socket.connect((self.host, self.port))
> Do I have to use explicit typecasting? How can this be achieved?
> 

This should work if you give correct arguments. For example:
Jython 2.1 on java1.4.2_06 (JIT: null)
Type "copyright", "credits" or "license" for more information.
 >>> import socket
 >>> s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 >>> s.connect(('www.google.com', 80))
 >>> s.close()

It would be helpful to know what self.host and self.port are. Put
print type(self.host), repr(self.host)
print type(self.port), repr(self.port)

in establishConnection() to print out the values you are using.

If host.port is the command line argument it is a string and you need to 
convert it to int with the int() function.

 >>> s.connect(('www.google.com', '80'))
Traceback (innermost last):
   File "<console>", line 1, in ?
   File "C:\Downloads\Java\jython-2.1\Lib\socket.py", line 135, in connect
TypeError: java.net.Socket(): 1st arg can't be coerced to 
java.net.InetAddress or String

Note it complains about the first arg; this may well be your error.

In general Python does not coerce argumentt types for you. Jython will 
translate between Java and Python types but it won't go as far as 
converting a String to an int.

Kent



More information about the Python-list mailing list