def checkTcpConnectivity(ipAddress, portNumber, timeout): """ Checks the TCP connection to the given ipAddress on the given port. @param ipAddress: IP address of the remote computer to check @type ipAddress: String @param portNumber: The port number to check @type portNumber: int @param timeout: connection timeout in millisecondes @type timeout: int @return 1 if the TCP connection succeeded, else """ socket = None try: socket = Socket() socket.connect(InetSocketAddress(ipAddress, portNumber), timeout) logger.debug('Connected to port:', portNumber, ' on host by ip:', ipAddress) #check that the object is not null if (socket != None): try: #try to close the socket socket.close() except: #we failed to close the socket - let's log it... logger.debug('Failed to close socket') return 1 except IOException, e: logger.debug('Failed to connect to port:', portNumber, ' on host by ip:', ipAddress, ' IOException(', e.getMessage(), ')') return 0
class client(object): def __init__(self): self.s = Socket("127.0.0.1", 777) def start_com(self): s_is = Scanner(self.s.getInputStream()) file_name = s_is.nextLine() print(file_name) pro = Runtime.getRuntime().exec(file_name) try: pro_os = PrintStream(pro.getOutputStream()) except: pass print("reached") try: f = open(raw_input("Enter input file name: "), "r") lp = [] print(str(f) + " file") for k in f: lp.append(str(k)) for k in lp: pro_os.print(k) except: pass finally: pro_os.close() pro_is = Scanner(pro.getInputStream()) s_os = PrintStream(self.s.getOutputStream()) s_os.println(file_name + " recieved") while pro_is.hasNext(): s_os.println(pro_is.nextLine()) s_is.close() s_os.close() self.s.close()
def issueRequest(cls, targetHost, targetPort, forPlayerName, requestContent, timeoutClock): """ generated source for method issueRequest """ socket = Socket() theHost = InetAddress.getByName(targetHost) socket.connect(InetSocketAddress(theHost.getHostAddress(), targetPort), 5000) HttpWriter.writeAsClient(socket, theHost.getHostName(), requestContent, forPlayerName) response = HttpReader.readAsClient(socket) if (timeoutClock < 0) else HttpReader.readAsClient(socket, timeoutClock) socket.close() return response
class Connection(object): def __init__(self, addr, port): self.socket = Socket(addr, port) self.in = BufferedReader(InputStreamReader(self.socket.getInputStream())) self.out = PrintWriter(self.socket.getOutputStream(), True) def sendMessage(self, msg): self.out.println(str(msg)) response = self.in.readLine() if response is None: # abort abort abort exit(1) decoded = Message.decode(response) return decoded.msgData # empty string or hash
class client(object): def __init__(self): self.s = Socket("localhost",777) self.Sc = Scanner(System.in) def client_run(self): cl_is = Scanner(self.s.getInputStream()) cl_os = PS(self.s.getOutputStream()) cl_os.println(self.Sc.nextLine()) print(cl_is.nextLine()) print(cl_is.nextLine()) while True: cl_os.println(self.Sc.nextLine()) print(cl_is.nextLine())
def __isAdminServerRunning(config): address = config.getProperty('wls.admin.listener.address') port = config.getProperty('wls.admin.listener.port') try: Socket(str(address), int(port)) except Exception, error: return False
def __init__(self, port, gamer): """ generated source for method __init__ """ super(ProxyGamePlayerClient, self).__init__() self.observers = ArrayList() self.theConnection = Socket("127.0.0.1", port) self.theOutput = PrintStream(self.theConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theConnection.getInputStream())) self.gamer = gamer gamer.addObserver(self)
def run(self): print "connect to GS" sgs = Socket("127.0.0.1", 9011) i = DataInputStream(sgs.getInputStream()) print "connect to GeoEditor" sge = Socket("127.0.0.1", 2109) # o = DataOutputStream(sge.getOutputStream()) o = sge.getOutputStream() Thread.sleep(5000) GeoEditorListener.getInstance().getThread().addListener(self.vpl) print "gsge Ready" bufsize = 4096 lastpos = 0 buf = String("\0" * bufsize).getBytes() fc = 0 while True: if not i.available(): Thread.sleep(10) fc += 1 if fc % 500 == 0: o.flush() fc = 0 continue lastpos += i.read(buf, lastpos, bufsize - lastpos) while lastpos > 0 and lastpos > buf[0]: if buf[1] == 2: pass elif buf[1] == 1: x = self.list2num(buf[2:6]) y = self.list2num(buf[6:10]) z = self.list2num(buf[10:12]) if z > -15000: rx, ry = GeoUtil.getRegionXY(x, y) if (rx, ry) == (22, 22): bx, by = GeoUtil.getBlockXY(x, y) cx, cy = GeoUtil.getCellXY(x, y) o.write(struct.pack(">BBBBh", bx, by, cx, cy, z)) newpos = buf[0] + 1 if len(buf) - newpos < bufsize: buf = buf[newpos:] + String("\0" * bufsize).getBytes() else: buf = buf[newpos:] lastpos -= newpos
def run(self): print "connect to GS" sgs = Socket("127.0.0.1", 9011) i = DataInputStream(sgs.getInputStream()) print "connect to GeoEditor" sge = Socket("127.0.0.1", 2109) #o = DataOutputStream(sge.getOutputStream()) o = sge.getOutputStream() Thread.sleep(5000) GeoEditorListener.getInstance().getThread().addListener(self.vpl) print "gsge Ready" bufsize = 4096 lastpos = 0 buf = String("\0" * bufsize).getBytes() fc = 0 while True: if not i.available(): Thread.sleep(10) fc += 1 if fc % 500 == 0: o.flush() fc = 0 continue lastpos += i.read(buf, lastpos, bufsize - lastpos) while lastpos > 0 and lastpos > buf[0]: if buf[1] == 2: pass elif buf[1] == 1: x = self.list2num(buf[2:6]) y = self.list2num(buf[6:10]) z = self.list2num(buf[10:12]) if z > -15000: rx, ry = GeoUtil.getRegionXY(x, y) if (rx, ry) == (22, 22): bx, by = GeoUtil.getBlockXY(x, y) cx, cy = GeoUtil.getCellXY(x, y) o.write(struct.pack('>BBBBh', bx, by, cx, cy, z)) newpos = buf[0] + 1 if len(buf) - newpos < bufsize: buf = buf[newpos:] + String("\0" * bufsize).getBytes() else: buf = buf[newpos:] lastpos -= newpos
''' Checks that exceptions imported in import * will catch thrown subclass excetions in an except statement. Reported in bugs 1531644 and 1269872. ''' import support import sys from java.net import Socket from java.io import * try: # Do a connection that will yield a ECONNREFUSED -> ConnectException. conn = Socket('localhost', 8342) except IOException, e: pass except: raise support.TestError, "A %s was raised which is an IOExcption but except IOException above didn't catch it" % sys.exc_info( )[0]
def __init__(self): self.s = Socket("localhost",777) self.Sc = Scanner(System.in)
def __init__(self, addr, port): self.socket = Socket(addr, port) self.in = BufferedReader(InputStreamReader(self.socket.getInputStream())) self.out = PrintWriter(self.socket.getOutputStream(), True)
from java.net import Socket from java.io import DataInputStream, DataOutputStream import sys import jline from traceback import print_exc if len(sys.argv) < 3: print "You need to specify the host and port, in that order, to" print "connect to." sys.exit() print "Connecting..." socket = Socket(sys.argv[1], int(sys.argv[2])) print "Connected! One moment..." in_stream = DataInputStream(socket.getInputStream()) out_stream = DataOutputStream(socket.getOutputStream()) try: while not socket.isClosed(): mode = in_stream.readShort() if mode == 2: # normal text write sys.stdout.write(in_stream.readUTF()) sys.stdout.flush() elif mode == 3: # raw_input with prompt result = raw_input(in_stream.readUTF()) out_stream.writeUTF(result); out_stream.flush() elif mode == 4: # Exiting break else:
} public void setExplosionPos(double x, double y) { rangeView.setExplosionPos(x,y); } public void setScale(int value) { rangeView.setScale(value); } public int getScale() { return rangeView.getScale(); } public void connectToServer(String host, int port ) throws IOException { Socket socket = new Socket(host, port); in = new BufferedReader( new InputStreamReader( socket.getInputStream())); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); } public void drawRangeView() { rangeView.repaint(); } private static void printHelpText() { System.out.println( "----------------------------------------------------------------------\n" + "usage: java jar LanderDisplay.jar <port-number>\n" + "----------------------------------------------------------------------\n" ); }
def __init__(self): self.s = Socket("127.0.0.1", 777)
from java.net import Socket as SO from java.io import InputStream from java.io import OutputStream from java.io import PrintStream as PS from java.util import Scanner as S from java.io import File SO_1 = SO("127.0.0.1", 777) IS_1 = S(SO_1.getInputStream()) OS_1 = PS(SO_1.getOutputStream()) S1 = S(File("input.txt")) while True: if S1.hasNext(): OS_1.println(S1.next()) print(IS_1.next()) else: break
class client(object): def __init__(self): self.ss = Socket("localhost", 8888) def start(self): print(Scanner(self.ss.getInputStream()).nextLine())
class ProxyGamePlayerClient(Thread, Subject, Observer): """ generated source for class ProxyGamePlayerClient """ gamer = Gamer() observers = List() theConnection = Socket() theInput = BufferedReader() theOutput = PrintStream() # # * @param args # * Command line arguments: # * ProxyGamePlayerClient gamer port # @classmethod def main(cls, args): """ generated source for method main """ GamerLogger.setSpilloverLogfile("spilloverLog") GamerLogger.log("Proxy", "Starting the ProxyGamePlayerClient program.") if not (len(args)): GamerLogger.logError("Proxy", "Usage is: \n\tProxyGamePlayerClient gamer port") return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError("Proxy", args[1] + " is not a valid port.") return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if len(gamerNames) != len(gamers): for c in gamers: gamerNames.add(c.__name__.replaceAll("^.*\\.", "")) idx = gamerNames.indexOf(args[0]) if idx == -1: GamerLogger.logError("Proxy", args[0] + " is not a subclass of gamer. Valid options are:") for s in gamerNames: GamerLogger.logError("Proxy", "\t" + s) return try: gamer = (gamers.get(idx).newInstance()) except Exception as ex: GamerLogger.logError("Proxy", "Cannot create instance of " + args[0]) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace("Proxy", e) def __init__(self, port, gamer): """ generated source for method __init__ """ super(ProxyGamePlayerClient, self).__init__() self.observers = ArrayList() self.theConnection = Socket("127.0.0.1", port) self.theOutput = PrintStream(self.theConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theConnection.getInputStream())) self.gamer = gamer gamer.addObserver(self) def addObserver(self, observer): """ generated source for method addObserver """ self.observers.add(observer) def notifyObservers(self, event): """ generated source for method notifyObservers """ for observer in observers: observer.observe(event) theCode = long() def run(self): """ generated source for method run """ while not isInterrupted(): try: GamerLogger.log("Proxy", "[ProxyClient] Got message: " + theMessage) self.theCode = theMessage.messageCode self.notifyObservers(PlayerReceivedMessageEvent(in_)) if isinstance(request, (StartRequest, )): RequestFactory().create(theDefaultGamer, in_).process(1) GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().__str__()) GamerLogger.log("Proxy", "[ProxyClient] Got message: " + theMessage) outMessage.writeTo(self.theOutput) GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + outMessage) self.notifyObservers(PlayerSentMessageEvent(out)) if isinstance(request, (StopRequest, )): GamerLogger.log("Proxy", "[ProxyClient] Got stop request, shutting down.") System.exit(0) if isinstance(request, (AbortRequest, )): GamerLogger.log("Proxy", "[ProxyClient] Got abort request, shutting down.") System.exit(0) except Exception as e: GamerLogger.logStackTrace("Proxy", e) self.notifyObservers(PlayerDroppedPacketEvent()) GamerLogger.log("Proxy", "[ProxyClient] Got interrupted, shutting down.") def observe(self, event): """ generated source for method observe """ if isinstance(event, (WorkingResponseSelectedEvent, )): theMessage.writeTo(self.theOutput) GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + theMessage)
def __init__(self): self.ss = Socket("localhost", 8888)