// make an incoming to the servent, wait a little, and then make sure // it asks for a connect back again public void testTCPExpireRequestsSent() throws Exception { drainAll(); for (int i = 0; i < 2; i++) { Socket s = new Socket("localhost", PORT); s.close(); Thread.sleep(100); // Socket must have said CONNECT BACK assertFalse(networkManager.acceptedIncomingConnection()); s = new Socket("localhost", PORT); s.getOutputStream().write(StringUtils.toAsciiBytes("CONNECT BACK\r\r")); Thread.sleep(500); s.close(); // Socket must have said CONNECT BACK assertTrue(networkManager.acceptedIncomingConnection()); // wait until the expire time is realized Thread.sleep(MY_EXPIRE_TIME + MY_VALIDATE_TIME + 1000); // it should send off more requests assertFalse(networkManager.acceptedIncomingConnection()); Message m = null; do { m = testUP[0].receive(TIMEOUT); } while (!(m instanceof TCPConnectBackVendorMessage)); } }
// QHandler handles incoming queries. public void run() { // hmmm.. this seems like potential bug. I want to check that query is not in table. But even // if query table contains key, // that does not necessarily mean it is in table, b/c two queries can have SAME HASHCODE VALUE. // I need to have some other means. // Will talk to Rusty @ this on Monday. if (!qt.containsKey(query)) // check that query is not already in table { Searcher.inform(query); // Give information to the Search Monitor panel NetworkManager.writeButOne(query.getIP(), query); /*Query is forwarded to all connected nodes except one from which query came. */ qt.put((Packet) query, query); // add query to table, indexed by its unique MessageID searchResult = SharedDirectory.search(query.getSearchString()); // check shared directory for query match numHits = searchResult.getSize(); if (numHits != 0) // package a query hit to send out if there is at least one query match { queryID = query.getMessageID(); port = Mine.getPort(); myIP = Mine.getIPAddress(); speed = Mine.getSpeed(); serventID = Mine.getServentIdentifier(); queryHit = new QueryHit(numHits, port, myIP, speed, searchResult, serventID, queryID); NetworkManager.writeToOne( query.getIP(), queryHit); // send qHit back to node that sent original query } } }
/** * Used whenever a player exits from the game. The most recent information stored for the player * will be saved into the database and any ties with the server will be removed as well. */ public void removePlayerData() { if (activeObjects.containsKey(Lobby.class)) { LobbyManager.getInstance().removeUser(getActiveObject(Lobby.class), player.getID()); } try { player.getSaveTimer().finish(); PlayerDAO.updateLogout(player.getID()); } catch (SQLException ex) { Log.println_e(ex.getMessage()); } GameServer.getInstance().removeActivePlayer(player.getID()); ResponseExitGame responseExitGame = new ResponseExitGame(); responseExitGame.setUserID(player.getID()); NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responseExitGame); ResponseChat responseChat = new ResponseChat(); responseChat.setMessage("[" + player.getUsername() + "] has logged off."); NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responseChat); ResponseGetPlayers responsePlayers = new ResponseGetPlayers(); responsePlayers.setPlayers(GameServer.getInstance().getActivePlayers()); NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responsePlayers); Log.printf("User '%s' has logged off.", player.getUsername()); }
// // 动�?下载 public boolean retrieveApkFromNet(Context context, String strurl, String filename) { boolean bRet = false; try { NetworkManager nM = new NetworkManager(this.mContext); bRet = nM.urlDownloadToFile(context, strurl, filename); } catch (Exception e) { e.printStackTrace(); } return bRet; }
/** * Connect or disconnect from server depending on internal flags. * * @param userRequest action was requested by user. * @return Whether state has been changed. */ public boolean updateConnection(boolean userRequest) { boolean available = isConnectionAvailable(userRequest); if (NetworkManager.getInstance().getState() != NetworkState.available || !available || disconnectionRequested) { ConnectionState target = available ? ConnectionState.waiting : ConnectionState.offline; if (state == ConnectionState.connected || state == ConnectionState.authentication || state == ConnectionState.connecting) { if (userRequest) connectionRequest = false; if (connectionThread != null) { disconnect(connectionThread); // Force remove managed connection thread. onClose(connectionThread); connectionThread = null; } } else if (state == target) { return false; } state = target; return true; } else { if (state == ConnectionState.offline || state == ConnectionState.waiting) { if (userRequest) connectionRequest = true; state = ConnectionState.connecting; connectionThread = new ConnectionThread(this); if (connectionSettings.isCustom()) connectionThread.start(connectionSettings.getHost(), connectionSettings.getPort(), false); else connectionThread.start(connectionSettings.getServerName(), 5222, true); return true; } else { return false; } } }
/** run once each game tick */ public void networkTick() { field_72584_h = false; currentTicks++; mcServer.theProfiler.startSection("packetflow"); theNetworkManager.processReadPackets(); mcServer.theProfiler.endStartSection("keepAlive"); if ((long) currentTicks - ticksOfLastKeepAlive > 20L) { ticksOfLastKeepAlive = currentTicks; keepAliveTimeSent = System.nanoTime() / 0xf4240L; keepAliveRandomID = randomGenerator.nextInt(); sendPacketToPlayer(new Packet0KeepAlive(keepAliveRandomID)); } if (chatSpamThresholdCount > 0) { chatSpamThresholdCount--; } if (creativeItemCreationSpamThresholdTally > 0) { creativeItemCreationSpamThresholdTally--; } mcServer.theProfiler.endStartSection("playerTick"); if (!field_72584_h && !playerEntity.playerHasConqueredTheEnd) { playerEntity.onUpdateEntity(); } mcServer.theProfiler.endSection(); }
// inherit doc comment public InetAddress getInetAddress() { try { return InetAddress.getByName(NetworkUtils.ip2string(networkManager.getAddress())); } catch (UnknownHostException e) { // may want to do something else here if we ever use this! return null; } }
protected u a(NetworkManager networkmanager) { if (networkmanager.e.notify.checkNewNotify == null) { b(orkManager.NetworkErrorCode.c.a()); return null; } else { networkmanager = new u(networkmanager.e.notify.checkNewNotify); networkmanager.a("userId", a); return networkmanager; } }
/** add by yejc 20130527 end */ public JSONObject sendRequest(final String content, String url) { NetworkManager nM = new NetworkManager(this.mContext); JSONObject jsonResponse = null; try { String response = null; synchronized (nM) { response = nM.SendAndWaitResponse(content, url /*Constants.server_url*/); } jsonResponse = new JSONObject(response); } catch (Exception e) { e.printStackTrace(); } if (jsonResponse != null) BaseHelper.log(TAG, jsonResponse.toString()); return jsonResponse; }
public NetServerHandler( MinecraftServer par1MinecraftServer, NetworkManager par2NetworkManager, EntityPlayerMP par3EntityPlayerMP) { this.mcServer = par1MinecraftServer; this.netManager = par2NetworkManager; par2NetworkManager.setNetHandler(this); this.playerEntity = par3EntityPlayerMP; par3EntityPlayerMP.playerNetServerHandler = this; }
@Override public SearchPerformer getPerformer(long token, String keywords) { KATSearchPerformer performer = null; if (NetworkManager.instance().isDataWIFIUp()) { performer = new KATSearchPerformer("kat.cr", token, keywords, DEFAULT_TIMEOUT); } else { LOG.info("No KATSearchPerformer, WiFi not up"); } return performer; }
@Test public void testHttpRetrieval() { try { String response = NetworkManager.retrieveRawContent(TEST_URL); Assert.assertNotNull(response); Assert.assertTrue(response.contains("I'm Feeling Lucky")); } catch (IOException e) { e.printStackTrace(); } }
public NetServerHandler( MinecraftServer minecraftserver, NetworkManager networkmanager, EntityPlayer entityplayer) { this.minecraftServer = minecraftserver; this.networkManager = networkmanager; networkmanager.a((NetHandler) this); this.player = entityplayer; entityplayer.netServerHandler = this; // CraftBukkit start server = minecraftserver.server; }
// This test checks that if _acceptedIncoming is false, connect back // messages are NOT sent public void testTCPExpireRequestsNotSent() throws Exception { drainAll(); for (int i = 0; i < 2; i++) { assertFalse(networkManager.acceptedIncomingConnection()); try { testUP[0].receive(TIMEOUT); } catch (InterruptedIOException expected) { } Thread.sleep(MY_EXPIRE_TIME + MY_VALIDATE_TIME); assertFalse(networkManager.acceptedIncomingConnection()); Thread.sleep(100); // now we should get the connect backs cuz it has been a while Message m = null; do { m = testUP[0].receive(TIMEOUT); } while (!(m instanceof TCPConnectBackVendorMessage)); } }
@Override public SearchPerformer getPerformer(long token, String keywords) { YifySearchPerformer performer = null; if (NetworkManager.instance().isDataWIFIUp()) { performer = new YifySearchPerformer("www.yify-torrent.org", token, keywords, DEFAULT_TIMEOUT); } else { LOG.info("No YifySearchPerformer, WiFi not up"); } return performer; }
public static Packet createRPCPacket(NetworkManager m, RPC rpc) throws IOException { if (!rpc.isInitialized()) { if (T.t) { T.error("RPC not initialized!"); } } Packet p = m.createPacketForSend(); p.writeByte(RPCFactory.getPacketIdFor(rpc)); p = rpc.serializeTo(p); return p; }
@Override public void run() { try { DataOutputStream toClient = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8")); int ch = 0; StringBuilder message = new StringBuilder(); while ((ch = fromClient.read()) != -1) { message.append(ch); } NetworkManager.post(NetworkManager.decodeFromXml(message.toString())); toClient.close(); fromClient.close(); } catch (IOException e) { e.printStackTrace(); } }
@Override public boolean ccTouchesBegan(MotionEvent event) { CGPoint touchPoint = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY())); if (btn_skill_bark_normal.getBoundingBox().contains(touchPoint.x, touchPoint.y) && gage >= Manager.required_gage_for_skill_bark) { SoundEngine.sharedEngine() .playEffect(CCDirector.sharedDirector().getActivity(), R.raw.effect_button); gage -= Manager.required_gage_for_skill_bark; hp_opponent -= Manager.damaged_hp_per_attack_bark; updateSkillBtns(); updateGageBar(); runAttackAnimation_mine(1); NetworkManager.getInstance().sendAttack(SkillType.BARK); } else if (btn_skill_bone_normal.getBoundingBox().contains(touchPoint.x, touchPoint.y) && gage >= Manager.required_gage_for_skill_bone) { SoundEngine.sharedEngine() .playEffect(CCDirector.sharedDirector().getActivity(), R.raw.effect_button); gage -= Manager.required_gage_for_skill_bone; hp_opponent -= Manager.damaged_hp_per_attack_bone; updateSkillBtns(); updateGageBar(); runAttackAnimation_mine(2); NetworkManager.getInstance().sendAttack(SkillType.BONE); /// * �������� ��� ���� ��� } else if (btn_skill_punch_normal.getBoundingBox().contains(touchPoint.x, touchPoint.y) && gage >= Manager.required_gage_for_skill_punch) { SoundEngine.sharedEngine() .playEffect(CCDirector.sharedDirector().getActivity(), R.raw.effect_button); gage -= Manager.required_gage_for_skill_punch; hp_opponent -= Manager.damaged_hp_per_attack_punch; updateSkillBtns(); updateGageBar(); runAttackAnimation_mine(3); NetworkManager.getInstance().sendAttack(SkillType.PUNCH); /// * �������� ��� ���� ��� } return super.ccTouchesBegan(event); }
public NetServerHandler( MinecraftServer minecraftserver, NetworkManager networkmanager, EntityPlayerMP entityplayermp) { connectionClosed = false; hasMoved = true; field_10_k = new HashMap(); mcServer = minecraftserver; netManager = networkmanager; networkmanager.setNetHandler(this); playerEntity = entityplayermp; entityplayermp.playerNetServerHandler = this; }
public void a(bn bn1) { if (!NetworkManager.a(b, bn1)) { return; } if (c <= 0) { NetworkManager.a(b, z.b(a)); return; } c = c - 1; NetworkManager.e(b).addFirst(NetworkManager.d(b)); try { Thread.sleep(NetworkManager.f(b)); return; } // Misplaced declaration of an exception variable catch (bn bn1) { return; } }
public NetServerHandler( MinecraftServer par1MinecraftServer, NetworkManager par2NetworkManager, EntityPlayerMP par3EntityPlayerMP) { serverShuttingDown = false; chatSpamThresholdCount = 0; creativeItemCreationSpamThresholdTally = 0; field_72587_r = true; field_72586_s = new IntHashMap(); mcServer = par1MinecraftServer; theNetworkManager = par2NetworkManager; par2NetworkManager.setNetHandler(this); playerEntity = par3EntityPlayerMP; par3EntityPlayerMP.serverForThisPlayer = this; }
/** addToSendQueue. if it is a chat packet, check before sending it */ public void sendPacketToPlayer(Packet par1Packet) { if (par1Packet instanceof Packet3Chat) { Packet3Chat packet3chat = (Packet3Chat) par1Packet; int i = playerEntity.getChatVisibility(); if (i == 2) { return; } if (i == 1 && !packet3chat.func_73475_d()) { return; } } theNetworkManager.addToSendQueue(par1Packet); }
private void listenNetworkMessagesUntilDisconnected() { if (socketType == SocketType.SERVER_SOCKET) { Gdx.app.debug(TAG, "Listening messages from the server."); } else if (socketType == SocketType.PLAYER_SOCKET) { Gdx.app.debug(TAG, "Listening messages from the player."); } InputStreamReader inputStream = new InputStreamReader(socket.getInputStream()); char[] readCharacter = new char[1]; // Read character will be stored in this array StringBuilder constructMessage = new StringBuilder(); while (running) { try { // Read one character from buffer or wait until there is a message in the buffer if (inputStream.read(readCharacter) == -1) { // Socket disconnected. running = false; } else { constructMessage.append(readCharacter[0]); // Message is too long? if (constructMessage.length() > NetworkManager.getInstance().NETWORK_MESSAGE_MAX_LENGTH_CHARACTERS) { constructMessage = new StringBuilder(); Gdx.app.debug(TAG, "WARNING: Network message was too long and was rejected!"); } if (readCharacter[0] == '>') { // End of the message reached, handle message if (socketType == SocketType.SERVER_SOCKET) { Gdx.app.debug(TAG, "Got message from the server: " + constructMessage); } else if (socketType == SocketType.PLAYER_SOCKET) { Gdx.app.debug( TAG, "Got message from the player " + player.getNumber() + ": " + constructMessage); } RTSProtocolManager.getInstance() .handleNetworkMessage(constructMessage.toString(), this); constructMessage = new StringBuilder(); } } } catch (Exception e) { Gdx.app.debug(TAG, "ERROR: while reading buffer: " + e.getMessage()); running = false; } } }
public void run() { Object var1 = NetworkManager.threadSyncObject; synchronized (NetworkManager.threadSyncObject) { ++NetworkManager.numWriteThreads; } while (true) { boolean var13 = false; try { var13 = true; if (!NetworkManager.isRunning(this.netManager)) { var13 = false; break; } while (NetworkManager.sendNetworkPacket(this.netManager)) {; } try { if (NetworkManager.getOutputStream(this.netManager) != null) { NetworkManager.getOutputStream(this.netManager).flush(); } } catch (IOException var18) { if (!NetworkManager.isTerminating(this.netManager)) { NetworkManager.sendError(this.netManager, var18); } var18.printStackTrace(); } try { sleep(2L); } catch (InterruptedException var16) {; } } finally { if (var13) { Object var5 = NetworkManager.threadSyncObject; synchronized (NetworkManager.threadSyncObject) { --NetworkManager.numWriteThreads; } } } } var1 = NetworkManager.threadSyncObject; synchronized (NetworkManager.threadSyncObject) { --NetworkManager.numWriteThreads; } }
protected u a(NetworkManager networkmanager) { if (networkmanager.e.post.listRelatedPost == null) { b(NetworkErrorCode.c.a()); return null; } networkmanager = new u(networkmanager.e.post.listRelatedPost); networkmanager.a("postStatus", "Published"); if (Globals.j()) { networkmanager.a("postStatus", "Auditing"); } networkmanager.a("postId", Long.valueOf(a)); networkmanager.a("postStatus", b); networkmanager.a("curUserId", c); networkmanager.a("offset", d); networkmanager.a("limit", e); return networkmanager; }
@Test public void testHttpPost() { Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put("userIds", "[\"frog\",\"toad\"]"); parameterMap.put( "message", "test Upload: " + Calendar.getInstance().getTime().toLocaleString()); parameterMap.put("applicationId", "SAS"); String response; try { response = NetworkManager.postData( "http://mci0lmobd001.empbenins.com:8080/MobileSecurity/services/notificationValidation/sendNotificationToUsers", parameterMap, null); Assert.assertNotNull(response); System.out.println(response); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
public void kickPlayerFromServer(String par1Str) { if (serverShuttingDown) { return; } else { playerEntity.mountEntityAndWakeUp(); sendPacketToPlayer(new Packet255KickDisconnect(par1Str)); theNetworkManager.serverShutdown(); mcServer .getConfigurationManager() .sendPacketToAllPlayers( new Packet3Chat( (new StringBuilder()) .append("\247e") .append(playerEntity.username) .append(" left the game.") .toString())); mcServer.getConfigurationManager().func_72367_e(playerEntity); serverShuttingDown = true; return; } }
@Test public void testHttpPostWithFile() { File testFile = new File("README"); Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put("author", "aaron"); parameterMap.put("comment", "test Upload: " + Calendar.getInstance().toString()); String response; try { response = NetworkManager.postDataWithFile( "http://localhost:8080/Services/services/upload/picture/", "fileToLoad", testFile, parameterMap, null); Assert.assertNotNull(response); System.out.println(response); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
@Override public void onTimer() { if (NetworkManager.getInstance().getState() != NetworkState.suspended) { Collection<ConnectionItem> reconnect = new ArrayList<ConnectionItem>(); for (ConnectionThread connectionThread : managedConnections) if (connectionThread.getConnectionItem().getState().isConnected() // XMPPConnection can`t be null here && !connectionThread.getXMPPConnection().isAlive()) { LogManager.i(connectionThread.getConnectionItem(), "forceReconnect on checkAlive"); reconnect.add(connectionThread.getConnectionItem()); } for (ConnectionItem connection : reconnect) connection.forceReconnect(); } long now = new Date().getTime(); Iterator<NestedMap.Entry<RequestHolder>> iterator = requests.iterator(); while (iterator.hasNext()) { NestedMap.Entry<RequestHolder> entry = iterator.next(); if (entry.getValue().isExpired(now)) { entry.getValue().getListener().onTimeout(entry.getFirst(), entry.getSecond()); iterator.remove(); } } }
public void a(String s) { NetworkManager.a(b, s); NetworkManager.a(b, null); }