Skip to content

Instantly share code, notes, and snippets.

@jlg
Created January 20, 2011 12:00
Show Gist options
  • Select an option

  • Save jlg/787794 to your computer and use it in GitHub Desktop.

Select an option

Save jlg/787794 to your computer and use it in GitHub Desktop.
diff --git a/py4j-python/src/py4j/java_gateway.py b/py4j-python/src/py4j/java_gateway.py
index 4d47694..53addec 100644
--- a/py4j-python/src/py4j/java_gateway.py
+++ b/py4j-python/src/py4j/java_gateway.py
@@ -666,6 +666,10 @@ class CallbackServer(Thread):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.lock = RLock()
self.is_shutdown = False
+
+ logger.info('Callback Server Starting')
+ self.server_socket.bind(('localhost', self.port))
+
def run(self):
"""Starts listening and accepting connection requests.
@@ -674,13 +678,12 @@ class CallbackServer(Thread):
is created and started automatically when a :class:`JavaGateway <py4j.java_gateway.JavaGateway>`
instance is created.
"""
+ with self.lock:
+ self.is_shutdown = False
+
+ self.server_socket.listen(5)
+ logger.info('Socket listening on' + str(self.server_socket.getsockname()))
try:
- with self.lock:
- self.is_shutdown = False
- logger.info('Callback Server Starting')
- self.server_socket.bind(('localhost', self.port))
- self.server_socket.listen(5)
- logger.info('Socket listening on' + str(self.server_socket.getsockname()))
while not self.is_shutdown:
socket, _ = self.server_socket.accept()
input = socket.makefile('r', 0)
@@ -831,4 +834,4 @@ register_output_converter(REFERENCE_TYPE, lambda target_id, gateway_client: Java
if PY4J_SKIP_COLLECTIONS not in os.environ or os.environ[PY4J_SKIP_COLLECTIONS].lower() not in PY4J_TRUE:
__import__('py4j.java_collections')
-
\ No newline at end of file
+
diff --git a/py4j-python/src/py4j/tests/java_callback_test.py b/py4j-python/src/py4j/tests/java_callback_test.py
index 77a7fbe..d0159a3 100644
--- a/py4j-python/src/py4j/tests/java_callback_test.py
+++ b/py4j-python/src/py4j/tests/java_callback_test.py
@@ -11,6 +11,7 @@ import logging
import subprocess
import time
import unittest
+import socket
def start_example_server():
@@ -209,6 +210,13 @@ class TestPeriodicCleanup(unittest.TestCase):
except:
self.assertTrue(True)
+class TestSocketInUse(unittest.TestCase):
+
+ def testSocketInUse(self):
+ port = 25334
+ s = socket.socket(socket.AF_INET)
+ s.bind(('localhost', port))
+ self.assertRaises(socket.error, JavaGateway, start_callback_server=True, python_proxy_port=port)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment