Skip to content

Commit

Permalink
Merge pull request #7 from qiujianzhong/main
Browse files Browse the repository at this point in the history
fix: prevent port conflicts when generating random ports
  • Loading branch information
debugtalk authored Jan 18, 2024
2 parents f96e349 + 4ed51fb commit c8ff433
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions funppy/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import random
import sys
import time
import socket
from concurrent import futures
from typing import Callable

Expand Down Expand Up @@ -45,13 +46,29 @@ def Call(self, request: debugtalk_pb2.CallRequest, context: grpc.ServicerContext
response = debugtalk_pb2.CallResponse(value=v)
return response

def check_available_port(port):
try:
# Create a socket object and attempt to bind it to the specified port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", port))
# The port is available, return False
return False
except OSError:
# The port is already in use, return True
return True

def serve():
# Start the server.
# Generate a random port
random_port = random.randrange(20000, 60000)

# Check if the random port is already in use
while check_available_port(random_port):
random_port = random.randrange(20000, 60000)

# Create the gRPC server and continue with the rest of your code
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
debugtalk_pb2_grpc.add_DebugTalkServicer_to_server(DebugTalkServicer(), server)

random_port = random.randrange(20000, 60000)
server.add_insecure_port(f'127.0.0.1:{random_port}')
server.start()

Expand All @@ -65,6 +82,5 @@ def serve():
except KeyboardInterrupt:
server.stop(0)


if __name__ == '__main__':
serve()

0 comments on commit c8ff433

Please sign in to comment.