More robust way of picking an unused local port

Fixes #584.
This commit is contained in:
Strahinja Val Markovic 2013-10-14 20:38:45 -07:00
parent b903867cdd
commit 98f549aeae
3 changed files with 12 additions and 4 deletions

View File

@ -31,12 +31,10 @@ import json
import subprocess
import logging
SERVER_NOT_FOUND_MSG = ( 'OmniSharp server binary not found at {0}. ' +
'Did you compile it? You can do so by running ' +
'"./install.sh --omnisharp-completer".' )
CS_SERVER_PORT_RANGE_START = 10001
class CsharpCompleter( Completer ):
"""
@ -118,7 +116,7 @@ class CsharpCompleter( Completer ):
""" Start the OmniSharp server """
self._logger.info( 'startup' )
self._omnisharp_port = CS_SERVER_PORT_RANGE_START + os.getpid()
self._omnisharp_port = utils.GetUnusedLocalhostPort()
solutionfiles, folder = _FindSolutionFiles( request_data[ 'filepath' ] )
if len( solutionfiles ) == 0:

View File

@ -22,6 +22,7 @@ import os
import sys
import signal
import functools
import socket
WIN_PYTHON27_PATH = 'C:\python27\pythonw.exe'
WIN_PYTHON26_PATH = 'C:\python26\pythonw.exe'
@ -48,6 +49,15 @@ def PathToTempDir():
return tempdir
def GetUnusedLocalhostPort():
sock = socket.socket()
# This tells the OS to give us any free port in the range [1024 - 65535]
sock.bind( ( '', 0 ) )
port = sock.getsockname()[ 1 ]
sock.close()
return port
def PathToPythonInterpreter():
# This is a bit tricky. Normally, sys.executable has the full path to the
# Python interpreter. But this code is also executed from inside Vim's

View File

@ -57,7 +57,7 @@ class YouCompleteMe( object ):
def _SetupServer( self ):
server_port = SERVER_PORT_RANGE_START + os.getpid()
server_port = utils.GetUnusedLocalhostPort()
with tempfile.NamedTemporaryFile( delete = False ) as options_file:
self._temp_options_filename = options_file.name
json.dump( dict( self._user_options ), options_file )