def send_mail(sender_address, mail_server, receiver_address, message): try: client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM) # set a 1 second timeout client_socket.settimeout(1.0) # connect to mail server client_socket.connect((mail_server, 25)) def send(string): """Helper function: fix newlines, encode and send a string""" final = string.replace("\n", "\r\n").encode("ascii") print "Sending " + final + "..." client_socket.send(final) return 0 def recv_and_check(expected=250): """Helper function: recive reply and check it's ok""" reply = client_socket.recv(2048) print "Got: ", reply code = int(reply.rstrip().split()[0]) if code != expected: raise Exception(reply) return 0 # get initial message from server recv_and_check(220) # send greeting send("HELO {}\n".format(sender_address.split("@")[1])) recv_and_check() # set sender address send("MAIL FROM: {}\n".format(sender_address)) recv_and_check() # set receiver address send("RCPT TO: {}\n".format(receiver_address)) recv_and_check() # prepare to send message send("DATA\n") recv_and_check(354) # send the message itself followed by terminator send("{}\n.\n".format(message)) recv_and_check() send("QUIT\n") recv_and_check(221) finally: client_socket.close() return 0
class Player: def __init__(self): self.client = Socket(AF_UNIX) socket = environ["MBROWSER_SOCKET"] self.client.connect(socket) def send(self, message): """Send message. """ # print(f"Worker to player: {message}") self.client.send((dumps(message) + '\n').encode("ascii")) def recv(self): """Return list of dict.""" data = self.client.recv(4096).decode("ascii") if not data: return None messages = [loads(line) for line in data.strip().split("\n")] # for message in messages: # print(f"Player to worker: {message}") return messages def loadfile(self, filename): if filename is None: self.send({"command": ["stop"]}) return self.send({"command": ["loadfile", filename]}) self.send({"command": ["set", "pause", "no"]}) def showtext(self, text): self.send({"command": ["show-text", text]}) def abloop(self): self.send({"command": ["ab-loop"]})
def start_client(): # Client (Player) Setup # import needed libraries from socket import socket as Socket from socket import AF_INET, SOCK_STREAM HOSTNAME = 'localhost' # on same host PORTNUMBER = 11267 # same port number BUFFER = 80 # size of the buffer SERVER = (HOSTNAME, PORTNUMBER) PLAYER = Socket(AF_INET, SOCK_STREAM) PLAYER.connect(SERVER) print(f'PLAYER >> Connected to SERVER over port {PORTNUMBER}.') while True: GUESS = input('PLAYER >> Guess the password: '******'SERVER >>', ANSWER) if ANSWER == 'You chose wisely.': break PLAYER.close()
def start_client(): # Client Setup # import needed libraries from socket import socket as Socket from socket import AF_INET, SOCK_STREAM HOSTNAME = 'localhost' # on same host PORTNUMBER = 12345 # same port number as server BUFFER = 1024 # size of the buffer SERVER = (HOSTNAME, PORTNUMBER) # create tuple of server address CLIENT2 = Socket(AF_INET, SOCK_STREAM) # create client socket CLIENT2.connect(SERVER) # connect client socket to server socket print(f'CLIENT2 >> Connected to SERVER over port {PORTNUMBER}.' ) # print verification string # loop until 'QUIT' is sent and received while True: MESSAGE2 = input( 'CLIENT2 >> Enter data you want to send or "QUIT" to exit-> ' ) # message to send to server CLIENT2.send(MESSAGE2.encode()) # send the encoded message to server REPLY2 = CLIENT2.recv(BUFFER).decode() # receive the servers reply print('SERVER >>', REPLY2) # print out the reply from server # break out of loop if QUIT is received if REPLY2 == 'QUIT': break print("CLIENT2 >> Closing Socket, GOODBYE." ) # print out break out of loop verification string CLIENT2.close() # close the socket
def server_connect(self, server_socket: socket.socket): """Connect proxied server socket""" uaddress = (self.config['uhost'], self.config['uport']) try: server_socket.connect(uaddress) except ConnectionRefusedError: raise UpstreamConnectionError('Connect error for %s:%s' % uaddress)
def output_worker(controller: 'SpotifyController', address: str, port: int, sock: socket.socket, stdout: Optional[IO[AnyStr]]): # Connect to address sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.connect((address, port)) # Clear stdout if stdout.seekable() and platform.system() == "Linux": stdout.seek(-8, os.SEEK_END) else: print("Cannot seek in stdout") # Start sending data try: while (not stdout.closed) or (not controller.stop_threads): # Read and send 0.25 seconds of audio sock.send(stdout.read(CHUNK_SIZE)) # Wait 250ms before reading the next chunk time.sleep(0.25) except (ConnectionResetError, BrokenPipeError, OSError): print( "Disconnected from bot. Either user disconnected, bot disconnected or there are connection problems." ) controller.on_bot_disconnect() finally: if sock is not None: sock.close() print(f"OutputWorker stopped")
class XMEye_Camera(Camera): def __init__(self, hass, client, channel, remote): super(XMEye_Camera, self).__init__() self._hass = hass self._client = client self._ffmpeg_manager = hass.data['ffmpeg'] self._remote = remote self._info = self._client.systeminfo() self._channel = int(channel) self._name = "%s_%i" % (self._info.board, channel) self._sock = Socket(AF_INET, SOCK_STREAM) # for streaming video self._sock.connect(self._remote) from dvrip.monitor import Stream self._reader = lambda: self._client.monitor(self._sock, self._channel, Stream.HD) self._in = None self._named_pipe = "/tmp/" + self._name if os.path.exists(self._named_pipe): os.unlink(self._named_pipe) os.mkfifo(self._named_pipe, S_IRUSR | S_IWUSR) self.setup_reader() import threading #self._thread = threading.Thread(target = async_reader_job, # args = (self._named_pipe, self._reader, self._hass,)) #self._thread.start() def setup_reader(self): if self._in is None: from dvrip.monitor import Monitor, MonitorAction, MonitorClaim, DoMonitor, MonitorParams, Stream monitor = Monitor(action=MonitorAction.START, params=MonitorParams(channel=self._channel, stream=Stream.HD)) claim = MonitorClaim(session=self._client.session, monitor=monitor) request = DoMonitor(session=self._client.session, monitor=monitor) self._in = self._client.reader(self._sock, claim, request) @property def should_poll(self) -> bool: return False @property def model(self): return self._info.board @property def name(self): return self._name async def async_camera_image(self): """Return a still image response from the camera.""" #self._hass.async_create_task(async_reader_job(self._named_pipe, self._in, self._hass)) from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg_manager.binary, loop=self.hass.loop) image = asyncio.run_coroutine_threadsafe( ffmpeg.get_image(self._named_pipe, output_format=IMAGE_JPEG)) return await image.result
def init(host: str = "127.0.0.1", sock: socket = None): try: sock = sock or socket() sock.connect((host, port)) except ConnectionRefusedError: raise ServerClosedError() return sock
def listen_server_words(s: socket.socket): """ This function is used to listen to incoming messages from other clients (actually from server). The function is used in the second thread. :param s: this is socket instance :return: """ while True: try: s.connect(('127.0.0.1', 8888)) except ConnectionRefusedError: print("Trying co connect to the remote server {} {} ...".format( '127.0.0.1', 8888)) time.sleep(2) else: print("Connection with {} {} was established".format( '127.0.0.1', 8888)) break # this is the main part of the function which listens to incomming messages while True: try: data = s.recv(1024) if data: data = data.decode('utf-8') income_data = data.split("|") income_data.pop() # remove empty part for m in income_data: from_whom, message = m.split("##") print(f"{from_whom} says: {message}") except ConnectionResetError: print("Session was finished by the remote server") break
def __send_to_target(self, next_stop: Packet, slave_client: socket.socket): try: a = next_stop.get( Packet.Options.REQUEST).encode().decode("unicode_escape") next_stop.set(a, Packet.Options.REQUEST) #if the target doesn't reply back, aka google.com:80 slave_client.settimeout(120) slave_client.connect((next_stop.get(Packet.Options.IP), next_stop.get(Packet.Options.PORT))) slave_client.sendall( (next_stop.get(Packet.Options.REQUEST)).encode()) try: reply = slave_client.recv(65536).decode() except: reply = "Error 502: Destination has not response back" except: reply = "Error 0xb042f: Destination is unvailable" slave_client.close() return reply
def new(cls, host, port, logger=None): logger = logger or logging.getLogger(__name__) sock = Socket() try: sock.connect((host, port)) except socket.error: return None return Connection(sock, logger)
def open_socket(client_socket: socket, ip_address: Union[IPv4Address, IPv6Address], port: int): """If a socket errors out and will try to reopen it""" try: client_socket.connect((ip_address.compressed, port)) except Exception as ex: error_message = f"{ex} occurred {ex.__class__}" logging.error(error_message)
def connect_to_server(my_socket: socket.socket, host: str, port: int): try: my_socket.connect((host, port)) print('Connection established') return True except socket.error as e: print(e) time.sleep(1) return False
def connect_socket(guest: socket, port: int): """ Connect a given socket to a given ip and port :param guest: The socket to connect. :param port: The port for the socket to connect. """ with suppress(Exception): guest.connect((constant.ip, port)) print(f"port {port} found")
def ping_node(ip: str, port: int, socket_obj: socket.socket): """ Utility function. Sends ping to a render node's socket. """ data = b"" socket_obj.connect((ip, port)) socket_obj.sendall(b"PING") data = socket_obj.recv(1024) socket_obj.close() return data == b"PONG"
def __init__(self, host, port, blocking=False): socket = Socket() for _ in range(100): # TODO: 10sec timeout, not configurable try: socket.connect((host, port)) break except ConnectionRefusedError: time.sleep(0.1) else: raise TensorforceError( "Remote socket connection could not be established.") super().__init__(connection=socket, blocking=blocking)
def main(): HOSTNAME = 'localhost' # on same host PORTNUMBER = 11267 # same port number BUFFER = 80 # size of the buffer DEALER = (HOSTNAME, PORTNUMBER) PLAYER = Socket(AF_INET, SOCK_STREAM) PLAYER.connect(DEALER) playGame(PLAYER, BUFFER) PLAYER.close()
def start( self ): Thread( target = self.readStdIn ).start( ) socket = Socket( AF_INET, SOCK_STREAM ) try: socket.connect( self.remotePeer.addr ) socket.send( 'CLIENT' ) self.remotePeer.onConnect( socket ) except SocketError: print 'failed to connect to server' os._exit( 1 )
def main(): try: server_address = ("127.0.0.1", 25565) socket = Socket() socket.connect(server_address) session = Session(socket, on_packet_recv) handshake(session, server_address, 498, 2) login(session, "1") except: pass
def attempt_connect(sock: socket.socket) -> None: """ Attempt to connect to localhost. :param sock: socket """ connected = False info('Waiting for DCS connection...') while not connected: try: sock.connect(('127.0.0.1', 7778)) info('Connected') connected = True except socket.error: sleep(2)
def connect(self, remotePeer): socket = Socket(AF_INET, SOCK_STREAM) msg = 'PEER{}'.format(str(self.localPeer.idx).rjust(2, '0')) try: while remotePeer.socket == None: socket.connect(remotePeer.addr) socket.send(msg) remotePeer.onConnect(socket) sleep( 2 ) # if connection mistakenly closed by remote peer, repeat # i.e. if remotr peer did not detect local peer's crash # and denied local peer's connection attempt on recovery except SocketError: pass # remotePeer down
async def connect(sock: socket.socket, address: Tuple) -> None: f = Future() # 将socket 设置为非阻塞模式 sock.setblocking(False) try: sock.connect(address) except BlockingIOError: pass def on_connected(): f.set_result(None) selector.register(sock.fileno(), EVENT_WRITE, on_connected) await f # 移除监听 selector.unregister(sock.fileno())
def main(): if len(sys.argv) <= 1: print "You need to specify the url of the application to display." return scheme, location = urlparse(sys.argv[1])[0:2] if scheme != "rtk": print ("Only rtk:// urls are supported for now. I might add an HTTP " "transport at some point in the future.") if ":" not in location: location += ":" + str(DEFAULT_PORT) host, port = location.split(":") port = int(port) socket = Socket() try: socket.connect((host, port)) except SocketError, e: print "Error while connecting: " + str(e) return
def call(self, *args, **kwargs): """ Remote call. """ socket = Socket(AF_INET, SOCK_STREAM) socket.connect(self.address) try: method = Document() method.name = self.name method.args = args method.kwargs = kwargs socket.send(method.dump()) reply = socket.recv(4096) result = Document() result.load(reply) return result finally: socket.close()
def call(self, *args, **kwargs): """ Remote call. """ socket = Socket(AF_INET, SOCK_STREAM) socket.connect(self.address) try: method = Document() method.name = self.name method.args = args method.kwargs = kwargs socket.send(method.dump()) reply = socket.recv(4096) result = Document() result.load(reply) return result finally: socket.close()
def get_page(server_address, request_string): try: client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_address, REMOTE_PORT)) client_socket.send(request_string.encode()) reply = bytes() while True: part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore") # print part_body if not len(part_body): break reply += part_body finally: client_socket.close() return reply
def _connect(self, tcp_socket: socket.socket) -> None: """ Creates socket and connects to given HOST and PORT. """ if self.current_reconnect_delay is not None: logger.info(f'Waiting {self.current_reconnect_delay} before connecting.') sleep(self.current_reconnect_delay) logger.info(f'Connecting to {self.host}:{self.port}.') tcp_socket.settimeout(CONNECTION_TIMEOUT) tcp_socket.connect((self.host, self.port)) logger.info(f'Connection established.') # Frame generator must be created here and passed to _authenticate() and _handle_connection(), because upon its # destruction it closes the socket. receive_frame_generator = unescape_stream(connection=tcp_socket) self._authenticate(receive_frame_generator, tcp_socket) # Reset delay and reconnection counter on successful authentication and set flag that connection is established. self.current_reconnect_delay = None self.reconnection_counter = 0 self.signing_service_daily_transaction_sum_so_far = self._get_signing_service_daily_transaction_sum_so_far() self._handle_connection(receive_frame_generator, tcp_socket)
def send(self): try: print("Submmiting files to MOSS") s = Socket() s.settimeout(5 * 60) s.connect((self.server, self.port)) s.send("moss {}\n".format(self.user_id).encode()) s.send("directory {}\n".format(self.options["d"]).encode()) s.send("X {}\n".format(self.options["x"]).encode()) s.send("maxmatches {}\n".format(self.options["m"]).encode()) s.send("show {}\n".format(self.options["n"]).encode()) s.send("language {}\n".format(self.options["l"]).encode()) recv = s.recv(1024) if recv == "no": s.send(b"end\n") s.close() raise Exception("send() => Language not accepted by server") for file_path, display_name in self.base_files: self.uploadFile(s, file_path, display_name, 0) index = 1 for file_path, display_name in self.files: self.uploadFile(s, file_path, display_name, index) index += 1 s.send("query 0 {}\n".format(self.options["c"]).encode()) response = s.recv(1024) s.send(b"end\n") s.close() return response.decode().replace("\n", "") except OSError as e: print("A problem was detected while sending to MOSS, retrying") print(e) time.sleep(60) return self.send()
def output_worker(address: str, port: int, sock: socket.socket, stdout): # Connect to address sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.connect((address, port)) # Start sending data try: while (not stdout.closed): # Read and send 0.25 seconds of audio sock.send(stdout.read(CHUNK_SIZE)) # Wait 250ms before reading the next chunk time.sleep(0.25) except (ConnectionResetError, BrokenPipeError, OSError): print( "Disconnected from bot. Either user disconnected, bot disconnected or there are connection problems." ) finally: if sock is not None: sock.close() print("OutputWorker stopped")
class XMEye_Camera(Camera): def __init__(self, hass, client, channel, remote): super().__init__() self._hass = hass self._client = client self._ffmpeg_manager = hass.data['ffmpeg'] self._remote = remote self._info = self._client.systeminfo() self._channel = channel self._name = "%s_%i" % (self._info.board, channel) self._sock = Socket(AF_INET, SOCK_STREAM) # for streaming video self._sock.connect(self._remote) from dvrip.monitor import Stream self._reader = lambda: self._client.monitor(self._sock, self._channel, Stream["HD"]) self._named_pipe = "/tmp/" + self._name if os.path.exists(self._named_pipe): os.unlink(self._named_pipe) os.mkfifo(self._named_pipe, S_IRUSR | S_IWUSR) @property def model(self): return self._info.board @property def name(self): return self._name async def async_camera_image(self): """Return a still image response from the camera.""" #self._hass.async_create_task(async_reader_job(self._named_pipe, self._reader)) from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg_manager.binary, loop=self.hass.loop) image = await asyncio.shield( ffmpeg.get_image(self._named_pipe, output_format=IMAGE_JPEG)) return image
def connect_with_protocol(s: sc.socket, hostname: str, port: int, http_protocol: str) -> sc.socket: # HTTPS case. Note that ssl.PROTOCOL_SSLv23 is deprecated, so we use ssl.PROTOCOL_TLS. if http_protocol == "HTTPS": s = ssl.wrap_socket(s, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLS, do_handshake_on_connect=True) s.connect((hostname, port)) # HTTP/2 case. elif http_protocol == "HTTP/2": ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2) # Declare this socket wants to advertise for h2 (HTTP/2) protocol. ssl_context.set_alpn_protocols(["h2"]) ssl_context.set_ciphers( "ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20") ssl_context.options |= ssl.OP_NO_COMPRESSION s.connect((hostname, port)) s = ssl_context.wrap_socket(s, server_hostname=hostname) # If HTTP2 and the returned protocol is not h2, we can't connect, throw exception. if s.selected_alpn_protocol() != "h2": raise Exception("Does not support HTTP/2") # HTTP/1.1 case. Connect without TLS. else: s.connect((hostname, port)) return s
class _InProgressSocketManager(object): """ This class does not actually work right now. It's something that I'm writing that will some day replace InputThread and OutputThread and allow Autobus to function using only a single thread for each Bus instance. So it's a work in progress, and it doesn't actually work right now. """ def __init__(self): # Set up the interrupt socket interrupt_server = Socket() interrupt_server.bind(("localhost", 0)) interrupt_server.listen(1) self.interrupt_writer = Socket() self.interrupt_writer.setblocking(False) self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1]) self.interrupt_reader = interrupt_server.accept() interrupt_server.shutdown(SHUT_RDWR) interrupt_server.close() self.interrupt_reader.setblocking(False) self.interrupt_writer.setblocking(False) def loop(self): pass def run_sync(self, function, timeout=None): q = Queue() @self.run_async def new_function(): q.put(function()) try: return q.get(timeout=timeout) except Empty: raise exceptions.TimeoutException def run_async(self, function): pass def interrupt(self): self.interrupt_writer.send(0)
def run(host: str, serv: int, username: str, password: str, args: List[str]) -> None: if len(args) != 1: usage() conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM)) sock = Socket(AF_INET, SOCK_STREAM) name, = args if name.startswith('/'): reader = lambda: conn.download(sock, name) elif name.startswith('monitor:'): if ';' not in name: name += ';hd' chanstr, strstr = name[len('monitor:'):].split(';', 1) try: channel = int(chanstr, base=0) except ValueError: usage() try: stream = Stream[strstr.upper()] except KeyError: usage() reader = lambda: conn.monitor(sock, channel, stream) else: usage() conn.connect((host, serv), username, password) sock.connect((host, serv)) try: file = reader() try: copyfileobj(file, stdout.buffer, length=256) except (BrokenPipeError, KeyboardInterrupt): pass finally: sock.close() conn.logout()
def connect_socket(self, sock: socket.socket) -> None: """Setup HTTP tunneling with the configured proxy. """ # Setup HTTP tunneling try: sock.connect((self._tunnel_host, self._tunnel_port)) except socket.timeout as e: raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e))) except socket.error as e: raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e))) # Send a CONNECT request with the host we want to tunnel to if self._tunnel_basic_auth_token is None: sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8')) else: sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format( self._server_host, self._server_port, self._tunnel_basic_auth_token ).encode('utf-8')) http_response = HttpResponseParser.parse_from_socket(sock) # Check if the proxy was able to connect to the host if http_response.status != 200: raise ProxyError(self.ERR_CONNECT_REJECTED)
def try_connect(addr: str, port: int, _socket: socket.socket, timeout: int) -> None: """ Function to try connection of a socket to a server Args: addr (str): Address of the server port (int): It's port _socket (socket.socket): Socket object you want to connect to the server timeout (int): Connection attempts """ for i in range(timeout): print("Attempt %d" % int(i + 1)) try: return _socket.connect((addr, port)) except Exception as e: print(e) sleep(1) print("Connection timed out after %s retries" % str(timeout)) exit(0)
from socket import socket as Socket from socket import AF_INET, SOCK_STREAM HOSTNAME = 'localhost' # on same host PORTNUMBER = 11267 # same port number BUFFER = 80 # size of the buffer DEALER = (HOSTNAME, PORTNUMBER) PLAYER = Socket(AF_INET, SOCK_STREAM) PLAYER.connect(DEALER) print('player is ready to guess') while True: GUESS = input('Give number : ') PLAYER.send(GUESS.encode()) ANSWER = PLAYER.recv(BUFFER).decode() print('>', ANSWER) if ANSWER == 'found the secret': break while True: datas = input('Enter data to send' ) PLAYER.send(datas.encode()) print('dealer received ' + datas) if datas == 'end': break PLAYER.close()
class AutobusConnection(AutobusConnectionSuper): """ A connection to an Autobus server. The typical way to use libautobus is to create an instance of this class and go from there. Right now, all interfaces that are to be made available must be specified before the connection is connected for the first time. They can be specified after, but this class won't register them until it reconnects. If the connection to the autobus server is lost, all currently-pending functions etc will raise an exception, and this class will attempt to re-establish a connection and re-register interfaces. Subscripting an instance of this class is the same as calling get_interface(). For example, a wrapper around the interface "example" on the server could be obtained with some_autobus_connection["example"]. Autobus provides introspection and additional information via the built-in autobus interface. You can access it with get_interface("autobus") or connection["autobus"]. Calling connection["autobus"].list_functions("autobus") will list all of the functions available on the autobus interface along with more documentation on how to use them. If reconnect is True (the default), the connection will reconnect itself and re-register all of its local interfaces and functions when it gets disconnected. It will continue attempting to reconnect indefinitely. If reconnect is False, it's up to the on_disconnect function (or some other functionality) to call the connect method when the connection is lost. If print_exceptions is True, any exceptions thrown by a local function invoked by a remote client will be printed with traceback.print_exc() before being sent back to the client that invoked the function. This is useful when a function is raising an unexpected error and more information about the error, such as its traceback, is needed. """ def __init__(self, host=None, port=None, reconnect=True, print_exceptions=False, on_connect=lambda: None, on_disconnect=lambda: None): """ Creates a new connection. This doesn't actually connect to the autobus server; use connect() or start_connecting() for that. """ if host is None: host = os.getenv("AUTOBUS_SERVER") if host is None: host = "localhost" if port is None: port = os.getenv("AUTOBUS_PORT") if port is None: port = DEFAULT_PORT if isinstance(port, basestring): port = int(port) self.socket = None self.host = host self.port = port self.reconnect = reconnect self.on_connect = on_connect self.on_disconnect = on_disconnect self.print_exceptions = print_exceptions self.on_connect_lock = RLock() self.interfaces = {} # Map of names to LocalInterface objects # representing interfaces we've registered self.is_shut_down = False self.send_queue = Queue() self.receive_queues = {} # Maps message ids expecting responses to the # corresponding queues waiting for the message response self.event_listeners = {} # Maps tuples containing an interface name # and an event name to a list of functions listening for the specified # event to fire on the server. At least one entry must be present in # each list in order for AutobusConnection to auto-register a # listener on the specified event on connect, even if it's as simple # as lambda: None. self.object_values = {} # Maps tuples containing an interface name and # an object name to the object's current value as sent by the server. # This dict gets replaced every time we disconnect. self.object_listeners = {} # Maps tuples containing an interface name # and an object name to a list of functions listening for changes in # that object. At least one entry must be present in each list in order # for AutobusConnection to auto-register a watch on the object on # connect, even if it's as simple as lambda: None. def shutdown(self): self.is_shut_down = True try: self.socket.shutdown(SHUT_RDWR) except: pass try: self.socket.close() except: pass def add_interface(self, name, interface=None): """ Adds an interface that will be automatically registered with the server on connecting. All methods that do not start with an underscore on the specified object will be registered on the interface as functions. The specified object's docstring, if it has one, will be used as the interface's documentation. If the specified interface is None, no functions will be registered on the interface. Either way, functions can later be registered with add_function. """ self.interfaces[name] = LocalInterface(name, inspect.getdoc(interface)) self.interfaces[name].connection = self if interface is not None: self.interfaces[name].add_all(interface) def add_function(self, interface_name, function_name, doc, function): """ Adds a function to the specified local interface. The interface must already have been registered with add_interface. The function will use the specified name and documentation (which must not be None: it should be the empty string if no documentation is available). When another client calls the specified function, the last argument to this function, which should be callable, will be invoked and its return value sent back to the invoking client. The function can raise an exception, which will be re-thrown on the client side. """ self.interfaces[interface_name].register_function(LocalFunction( function_name, doc, function)) def add_event_listener(self, interface_name, event_name, function): """ Adds a function that will be notified when the specified remote event is fired. This function is not thread-safe and should generally only be called before the first connection to the server is created. The specified function should accept a number of arguments corresponding to the number of arguments sent when the remote client fires the event. You'll usually have to consult the event's documentation. """ if hasattr(function, "fired"): # We're on Jython and the function is # an instance of EventListener function = function.fired event_spec = interface_name, event_name if event_spec not in self.event_listeners: self.event_listeners[event_spec] = [] self.event_listeners[event_spec].append(function) def add_event(self, interface_name, event_name, doc): """ Adds a local event to the specified interface. The LocalEvent instance created for the event will be returned. """ event = LocalEvent(event_name, doc) self.interfaces[interface_name].register_event(event) return event def add_object_watch(self, interface_name, object_name, function): """ Adds a function that will be notified when the specified remote object's value changes. add_object_watch is not thread-safe and should generally only be called before the first connection to the server is created. The function should accept one argument. This argument will be the new value of the object. The function must not interact with Autobus. If it does, deadlock will likely result, as the input thread, which receives packets from the server (such as responses to function calls), blocks while this function is invoked. If you need to interact with Autobus (for example, to call functions etc), the function you supply should start a new thread to do so. """ if hasattr(function, "changed"): # We're on Jython and the function # is an instance of ObjectListener function = function.changed object_spec = interface_name, object_name if object_spec not in self.object_listeners: self.object_listeners[object_spec] = [] self.object_listeners[object_spec].append(function) def add_object(self, interface_name, object_name, doc, value): """ Adds a shared object to the specified interface. The LocalObject instance created for the object will be returned. """ object = LocalObject(object_name, doc, value) self.interfaces[interface_name].register_object(object) return object def start_connecting(self): """ Calls connect(None) in a new thread. Any exception thrown by the call to connect(None) is discarded without being printed to stdout. """ def target(): try: self.connect(attempts=None) except: pass Thread(target=target).start() def connect(self, attempts=1): """ Connects to the Autobus server. The specified number of attempts will be made to re-establish a connection, each time waiting an amount of time that increments itself up to 20 seconds. If attempts is None, an infinite number of attempts will be made. Once a connection has been established, this method returns. If it fails to establish a connection, an exception will be raised. """ if attempts == 0: attempts = None progress = 0 delay = 0.1 delay_increment = 1.5 while (attempts is None or progress < attempts) and not self.is_shut_down: progress += 1 delay *= delay_increment if delay > 20: delay = 20 self.socket = Socket() try: self.socket.connect((self.host, self.port)) except: sleep(delay) continue with self.on_connect_lock: self.connection_established() return raise Exception("Couldn't connect") # messagearrived, inputclosed, readnextmessage def connection_established(self): # print "Processing established connection..." self.input_thread = InputThread(self.socket, self.message_arrived, self.input_closed) self.output_thread = OutputThread(self.socket, self.read_next_message, self.message_write_finished) self.send_queue = Queue() # clear the send queue self.receive_queues = {} self.input_thread.start() self.output_thread.start() # print "Registering interfaces with the server..." for interface in self.interfaces.values(): self.send(create_message(RegisterInterfaceCommand, NOTIFICATION, name=interface.name, doc=interface.doc)) message = create_message(RegisterFunctionCommand, NOTIFICATION, interface_name=interface.name, name=[], doc=[]) for function in interface.functions.values(): message["name"].append(function.name) message["doc"].append(function.doc) self.send(message) for event in interface.events.values(): self.send(create_message( RegisterEventCommand, NOTIFICATION, interface_name=interface.name, event_name=event.name, doc=event.doc)) for object in interface.objects.values(): self.send(create_message( RegisterObjectCommand, NOTIFICATION, interface_name=interface.name, object_name=object.name, doc=object.doc, value=encode_object(object.value))) for interface_name, event_name in self.event_listeners.keys(): self.send(create_message( RegisterListenerCommand, NOTIFICATION, interface_name=interface_name, event_name=event_name)) for interface_name, object_name in self.object_listeners.keys(): message = create_message( WatchObjectCommand, COMMAND, interface_name=interface_name, object_name=object_name) self.send(message) # I used to send this as a query and set the # resulting value into the object, but this caused a race condition # where another value arriving as a SetObjectCommand before the # logic in this method could get the new value set into the object # would cause the object to be reset to its initial value. So for # now, we're processing the WatchObjectResponse in message_arrived # the same as we process SetObjectCommand instances from the # server, which fixes the race condition. That's why it's a command # but we're not querying for the response. # That's it! Now we run the user's on_connect function. self.on_connect() def message_arrived(self, message): # print "Message from the server arrived: " + str((message)) + "\n\n" queue = self.receive_queues.get(message["message_id"], None) if queue is not None: queue.put(message) try: del self.receive_queues[message["message_id"]] except KeyError: pass return if message["action"] == RunFunctionCommand: interface_name = message["interface_name"] function_name = message["function"] arguments = [decode_object(arg) for arg in message["arguments"]] try: if function_name.startswith("_"): raise Exception("Function names starting with _ are " "not allowed") interface = self.interfaces[interface_name] function = interface.functions[function_name] except Exception, e: if self.print_exceptions: print_exc() self.send(create_message(RunFunctionResponse, message, return_value=encode_object(e))) def process(): try: return_value = function.function(*arguments) except: if self.print_exceptions: print_exc() _, return_value, _ = sys.exc_info() #@UndefinedVariable self.send(create_message(RunFunctionResponse, message, return_value=encode_object(return_value))) if function.start_thread: Thread(target=process).start() else: process() return if message["action"] == FireEventCommand: interface_name = message["interface_name"] event_name = message["event_name"] arguments = message["arguments"] event_spec = (interface_name, event_name) self.fire_event_listeners(event_spec, [decode_object(o) for o in arguments]) return if message["action"] in (SetObjectCommand, WatchObjectResponse): interface_name = message["interface_name"] object_name = message["object_name"] value = message["value"] object_spec = (interface_name, object_name) self.object_values[object_spec] = decode_object(value) self.notify_object_listeners(object_spec) return if message["action"] == PingCommand: self.send(create_message(PingResponse, message)) print "Not processing message for action " + message["action"]
def connect_socket(self, sock: socket.socket) -> None: sock.connect((self._server_ip_addr, self._server_port))
class GoBotClient: def __init__(self, IP='127.0.0.1', port=5005): self.IP = IP self.port = port self.player = None self.turn = 2 def start_game(self, player, size): self.player = player print 'beginning game as player %d' % player self.GoBot = GoBot(0 if player == 2 else 1) if player == 2: self.make_move('pass') def made_move(self, i, j): self.turn = 1 if self.turn == 2 else 2 def passed_turn(self): self.turn = 1 if self.turn == 2 else 2 def make_move(self, move): if self.turn == self.player: if move != 'pass': gobot_move = self.GoBot.make_move((move[1], move[0])) else: gobot_move = self.GoBot.make_move('pass') self.send('MAKEMOVE %d %d' % (gobot_move[1], gobot_move[0])) def run(self): self.connect_to_server() while True: if self.listen(): print "Disconnected from server\n" return def receive(self, data): print 'receiving [%s]' % data data = data.split() if not data: return message = data[0] if message == 'BEGINGAME': self.start_game(int(data[1]), int(data[2])) elif message == 'MADEMOVE': i, j = map(int, data[1:3]) self.made_move(i, j) if self.turn == self.player: self.make_move((i, j)) elif message == 'PASSEDTURN': self.passed_turn() if self.turn == self.player: self.make_move('pass') elif message == 'GAMEOVER': a, b = map(int, data[1:3]) self.game_over(a, b) elif message == 'FINISH': return True def send(self, data): print 'sending %s' % data self.skt.send(data) def connect_to_server(self): BUFFER_SIZE = 1024 self.skt = Socket(AF_INET, SOCK_STREAM) self.skt.connect((self.IP, self.port)) self.skt.setblocking(0) def listen(self): BUFFER_SIZE = 1024 try: data = self.skt.recv(BUFFER_SIZE) except SocketError: pass else: if not data: return for line in data.split('\n'): if self.receive(line): return True
class GoClient: def __init__(self, IP='127.0.0.1', port=5005): self.root = tk.Tk() self.IP = IP self.port = port self.players = [] def start_game(self, player, size): self.players.append(player) self.board = Board(size) print 'beginning game as player %d' % player self.make_display() self.gui.start_game() def made_move(self, i, j): self.board.place_piece(i, j) self.gui.made_move() def passed_turn(self): self.board.pass_turn() self.gui.passed_turn() def game_over(self, score1, score2): self.gui.set_message('Game Over, Black: %d White: %d' % (score1, score2)) self.board.gameover = True def on_click(self, i, j): if self.board.turn in self.players: self.send('MAKEMOVE %d %d' % (i, j)) # self.receive('MADEMOVE %d %d' % (i, j)) def on_quit(self): send('QUIT') self.gui.parent.destroy() def on_pass(self): if self.board.turn in self.players: self.send('PASSTURN') def run(self): # self.start_game(1) # self.start_game(2) self.connect_to_server() self.root.title('Python Online Five-In-A-Row') # root.resizable(0,0) self.root.mainloop() # print 'received data:', data def make_display(self): self.gui = BoardGui(parent=self.root, board=self.board, players=self.players) self.gui.on_click.append(self.on_click) self.gui.on_pass.append(self.on_pass) self.gui.pack(side='top', fill='both', expand='true', padx=4, pady=4) def receive(self, data): print 'receiving [%s]' % data data = data.split() if not data: return message = data[0] if message == 'BEGINGAME': self.start_game(int(data[1]), int(data[2])) elif message == 'MADEMOVE': i, j = map(int, data[1:3]) self.made_move(i, j) elif message == 'PASSEDTURN': self.passed_turn() elif message == 'GAMEOVER': a, b = map(int, data[1:3]) self.game_over(a, b) def send(self, data): print 'sending %s' % data self.skt.send(data) def connect_to_server(self): BUFFER_SIZE = 1024 self.skt = Socket(AF_INET, SOCK_STREAM) self.skt.connect((self.IP, self.port)) self.skt.setblocking(0) def listen(): try: data = self.skt.recv(BUFFER_SIZE) except SocketError: pass else: if not data: return for line in data.split('\n'): self.receive(line) self.root.after(500, listen) listen()