1#!/usr/bin/env python 2 3# Copyright JS Foundation and other contributors, http://js.foundation 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import socket 18import select 19 20# pylint: disable=too-many-arguments,superfluous-parens 21class Socket(object): 22 """ Create a new socket using the given address family, socket type and protocol number. """ 23 def __init__(self, address, socket_family=socket.AF_INET, socket_type=socket.SOCK_STREAM, proto=0, fileno=None): 24 self.address = address 25 self.socket = socket.socket(socket_family, socket_type, proto, fileno) 26 27 def connect(self): 28 """ 29 Connect to a remote socket at address (host, port). 30 The format of address depends on the address family. 31 """ 32 print("Connecting to: %s:%s" % (self.address[0], self.address[1])) 33 self.socket.connect(self.address) 34 35 def close(self): 36 """" Mark the socket closed. """ 37 self.socket.close() 38 39 def receive_data(self, max_size=1024): 40 """ The maximum amount of data to be received at once is specified by max_size. """ 41 return self.socket.recv(max_size) 42 43 def send_data(self, data): 44 """ Send data to the socket. The socket must be connected to a remote socket. """ 45 return self.socket.send(data) 46 47 def ready(self): 48 """ Monitor the file descriptor. """ 49 result = select.select([self.socket], [], [], 0)[0] 50 51 return self.socket in result 52