LoadRunner技巧之脚本设计

Posted on

LoadRunner技巧之脚本设计

           LoadRunner技巧之脚本设计   发布于2013-8-6   在做性能测试时,我们可能会遇到各种不同的业务需求与用户行为,在一个系统或网站中,每个用户的操作都不完全一样。我们如何来模拟这此用户的行为?经验与能力有限,我这里也做个简单的分析。

Action 介绍

在此之前,我们先来介绍一个Action ,Action就像是一个函数包,将用户操作根据类别存放在不同的函数中,当选择完HTTP协议后,VuGen将自动生成脚本的框架。

默认脚本目录有三部分组成:

1.Vuser_int

2.Action

3.Vuser_end

简单有的来说,我们可以把他们看成三个程序文件,他们依次按照Vuser_int --->Action--->Vuser_end 的顺序执行,存放于Action中的脚本可以循环执行(可以设置循环次数)

在脚本录制之前,我们可以设置将脚本录制在哪一部分:

在脚本录制的过程中,我们可以选择切换脚本的存放位置:

在脚本左侧右键添加新的action部分:

在菜单栏Vuser ---> run-time setting ,选择Run logic 选项,可以设置Action部分的循环次数。

下面简单介绍如何使用参数化、action设置和业务用户比例等进行性能测试。

场景一:

一个用户访问WebTours (loadrunner 自带程序)首页,做两次登录与退出

1、vuser_init部分录制访问webrours首页: vuser_init() { web_url("WebTours", "URL=http://127.0.0.1:2080/WebTours", "Resource=0", "RecContentType=text/html", "Referer=", "Snapshot=t30.inf", "Mode=HTML", LAST); web_url("header.html", "URL=http://127.0.0.1:2080/WebTours/header.html", "Resource=0", "RecContentType=text/html", "Referer=http://127.0.0.1:2080/WebTours/", "Snapshot=t31.inf", "Mode=HTML", LAST); web_url("welcome.pl", "URL=http://127.0.0.1:2080/WebTours/welcome.pl?signOff=true", "Resource=0", "RecContentType=text/html", "Referer=http://127.0.0.1:2080/WebTours/", "Snapshot=t32.inf", "Mode=HTML", EXTRARES, "Url=../favicon.ico", "Referer=", ENDITEM, LAST); }

2、将脚本录制部分切换到Action 部分,录制用户登录与退出

Action() { web_submit_data("login.pl", "Action=http://127.0.0.1:2080/WebTours/login.pl", "Method=POST", "Referer=http://127.0.0.1:2080/WebTours/nav.pl?in=home", "Mode=HTML", ITEMDATA, "Name=userSession", "Value=110416.933414338fzHQfHVpAVcfDtAHHptczAHf", ENDITEM, "Name=username", "Value={username}", ENDITEM, //参数化用户名 "Name=password", "Value={password}", ENDITEM, //参数化密码 "Name=JSFormSubmit", "Value=on", ENDITEM, LAST); web_submit_data("login.pl_2", "Action=http://127.0.0.1:2080/WebTours/login.pl", "Method=POST", "RecContentType=text/html", "Referer=http://127.0.0.1:2080/WebTours/nav.pl?in=home", "Snapshot=t33.inf", "Mode=HTML", ITEMDATA, "Name=userSession", "Value=110416.933414338fzHQfHVpAVcfDtAHHptczAHf", ENDITEM, "Name=username", "Value=test", ENDITEM, "Name=password", "Value=123456", ENDITEM, "Name=JSFormSubmit", "Value=on", ENDITEM, "Name=login.x", "Value=56", ENDITEM, "Name=login.y", "Value=4", ENDITEM, LAST); return 0; }

run-time setting 的Run logic 选项,设置Action 运行两次。

运行脚本结束,可以通过菜单栏view--->Test Results 来查看运行的结果是否正确

场景二:

一个用户登录一个系统,做3次查询,5次插入,退出。

这里我就不做详细介绍了,需要的注意点是,可以在run-time setting 的Run logic 选项中点击insert Block 添加快,双击Block 设置循环次数。

将我们的查询操作与插入操纵分别存放在两个迭代块(block)中

我们还可以设置迭代之间的间隔,run-time setting 的pacing

场景三 :

这个场景跟用户操作比例有关系业务有关,一个网站,在线用户中,有80% 用户发表文章,20%的用户上传相片。

那么,我可以分别录制两个脚本,第一脚本,用户操作发表文章;第二个脚本,用户操作上传相片。

将两个脚本导入Controller 控制器中。

注意勾选 use the percentage mode to distribute the vusers among the scrpts ,不然无法分配脚本用户比例。

我们可以为脚本分配不同的用户比例来运行。

这里只是提供一个思路,我们可以根据这些设置(或叫技巧)结合我们的业务需求来进行脚本与场景设计。

基于jsqlparser做javacc二次开发

Posted on

基于jsqlparser做javacc二次开发

yiihsia[互联网后端技术]

好记性不如烂博客,nosql、分布式架构、搜索引擎、海量数据处理。

基于jsqlparser做javacc二次开发

2012年6月19日 yiihsia 发表评论 阅读评论 689

jsqlparser是个开源的sql解析方案,基于javacc,提供比较全面的sql解析和反转,对于复杂的sql解析可以基于它扩展。http://jsqlparser.sourceforge.net/

最简单的实现,就是传入一条sql,jsqlparser解析后返回一个对象。我们只需要操作这个对象就行,一般都能满足需求,但是有时间还不能满足,需要自己扩充同时不能影响原来的解析。

罗列下扩展的地方:

1、支持中文

2、支持Create Database语法

3、支持Alter Table语法

4、drop table语法中支持table带scheme

修改后的jj文件下载地址:http://code.google.com/p/my-jsqlparser/downloads/list

使用方式:

1、替换原来net.sf.jsqlparser.parser目录下的JSqlParserCC.jj文件

2、在eclipse下点击该文件选择compile with javacc

3、运行原来工程的单元测试,是否有异常

———————————— 2012.7.31更新———————————-

1、添加drop index语法 , drop index scheme.table.indexname

2、添加create index语法, create [UNIQUE|PRIMARYKEY|ADDITIONAL] [索引类型hashmap...] index indexname on table(column)

注:自己的项目中需要根据分片规则修改表名,为了方便直接在表名前后加上/#,不需要迭代遍历。造成toString()的时候表名有/#, 可以修改net.sf.jsqlparser.schema.Table的getWholeTableName方法

分类: Java, 数据库 标签: java, javacc

你可能感兴趣

评论 (72) 发表评论

HeatherKline23

2013年3月12日05:09 | /#1

回复 | 引用 People in the world get the loans from various creditors, because it is easy and fast.

OuuYwa

2013年3月18日04:55 | /#2

回复 | 引用 If a mother or father lends a child $150,000, parents must declare a figure that represents the interest income with their tax return Having said that, if applying out services it really is important to note that you can spend out between http://www.paydayloansonline9.co.uk/ – payday loans online uk Speed: it is one thing that can help you in making the best choice among the Canadian companies providing the short term loans In comparison to other education loans, emergency student education loans offer less of your budget and have short terms

payday loans

2013年4月17日16:17 | /#3

回复 | 引用 In caseswhere the borrower runs a business out of the commercial property bywhich the loan is placed, the lender may require additional coverage payday loans uk. Besides as a house owner quite a few financial institutions can accept an automobile, shares or another expensive property that can be used because collateral

Those investigations exist for various access place classes You only desire it at their bargain price, which cost just isn’t going to be in relation to for long

payday loans uk

2013年4月17日18:54 | /#4

回复 | 引用 It can be one of the most comprehensive and reliable machines to diseases plus injuries, and much more preventive health purposes payday loans. ADEA itself contains a fee decrease program available for those students in extreme financial want

nbsp; The treatment of investing in instant payday loans online pretty iseasy and also secure as it’s completed on the net with ease of your home Behind your southeastern pillar, next to the Caravan Shotgun 宝贝价格

payday loans online

2013年4月17日21:36 | /#5

回复 | 引用 However, there many other ways to help make fast money on line, like Forex trading, MLM marketing, Cost per action marketing and Marketing via email pay day loans. If your personal bankruptcy action was under Chapter seven, you may be suitable if your generate was 2 yrs ago, you currently have steady occupation, and have correctly established and also maintained completely new credit lines

nbsp; These loans will be formulated by preserve in mind your current emergencyneeds which comes up in the middle of of the calendar month without any clue You can still get the best selection of products in these shelves, of course, in the super good deal 宝贝价格

payday loans uk

2013年4月18日00:44 | /#6

回复 | 引用 Home loan throughout India have been one of the best demands from a numerous people payday loans. When you can get by performing a traditional re-finance, you should unquestionably do that very first, but if it’s not possible to refinance like that, you might want to contemplate Fannie Mae’s new Refi And also program taking into consideration out in 04

Details of the particular registered owner, along with chassis number, present-day registration tag, engine selection and other facts will be integrated The quantities of money that could be availed with next day payday cash loans range from One hundred to a maximum of 1500 and the repayment period can not go beyond 14 next day it has been utilized 宝贝价格

payday loans uk

2013年4月18日00:58 | /#7

回复 | 引用 Payday cash loans are also viewed as the best choice for people who are tagged with a low credit score performance payday loans uk. In some instances, the financial institution’s collection practices have been violent or in infringement of the regulation

Advisable to get money via this setting is to save lot campaigns, energy, time and the considerably desired a person’s extra expenses Rise and Fall, Fall and rise, no end to the present rhythm,Me wont make rejection more 宝贝价格

Fulleyqueuerm

2013年4月19日01:17 | /#8

回复 | 引用 This kind of advance will give you a backside of small amount of cash payday loans. You can even sign up for loan even though you have poor credit rating providing you meet the eligibility criteria

It’s extremely uncomfortable and a lot people will not be quite guaranteed how to approach the patient This is the time to get started along with hard funds lending 宝贝价格

Fulleyqueuerm

2013年4月19日01:28 | /#9

回复 | 引用 Think of this because case study students recruit throughout Stacee college and university using university, eliminates a financing to be with her principal the bride and groom of several years related with pay out while research projects payday loan. You can use it to repay your healthcare expenses, grocery bills, mobile expenditures, monthly house rent, child�s school fee as well as whatever you want to

Boost fee loaning companies is often rather convincing which enables it to put up by far the most professional regarding fronts towards you world Their researchers have convinced these people that many new customers will run its balances over ever before, in the event given what they have to think can be a deal 宝贝价格

Fulleyqueuerm

2013年4月19日03:35 | /#10

回复 | 引用 Running a vehicle is expensive, not simply the petrol, but the offering, maintenance as well as tax pay day loan. – Many current museums, specially in Western countries have collection agencies of virtually colonial amounts but deal with funding shortages

Do not get despaired, with the assistance of Want Loans, we can easily certainly lift you out of one’s monetary ab exercises For those who have paid in advance for the policy that you are going to cancel, then you certainly should be able to obtain prompt reclaim 宝贝价格

Fulleyqueuerm

2013年4月19日08:31 | /#11

回复 | 引用 Source Ones Groceries Nicely Groceries take up a huge slice of your income since these mostly involve essentials for instance food, toiletries and cleaning products and solutions pay day loans. In summary, debt consolidation reduction loans give you a way to aid individuals decrease their credit debt and their monthly installments by incorporating high interest credit card obligations into a single loan

Doing an unsanctioned overdraft position will not only view you incur rates but will additionally further harm your by now tarnished financial record Money lenders provide these individuals a value and that computer code is e-mailed in their eyes by all those applicants 宝贝价格

Fulleyqueuerm

2013年4月19日08:38 | /#12

回复 | 引用 Simply because you’ve never organised a credit card and also taken out an unsecured loan doesn’t mean you have good credit pay day loans. PMI property finance loan insurance is just one solution to this problem by way of insuring a lender’s interests in affording the mortgage

As long as your current commenting is insightful and not viewed as unsolicited mail, there is a likelihood that a dialog can be reach up among you and the various other blogger It is advisable to Stop questioning the same questions can i easy and adjusting for i will be making money online, start training your mind 宝贝价格

Fulleyqueuerm

2013年4月19日08:59 | /#13

回复 | 引用 The thing along with shopping for a home loan, versus shopping for a home and then going with no matter what seller delivers as income vehicle, is the fact that when you shop for just a home loan, you will be dealing right with loan companies whose single purpose is always to make money off of your loan uk pay day loans. Your credit ranking does not present as a deterrent to acquire them

It gives consumer credit issuers including banks and mortgage firms information on how you make payment for your bills == Pros with Adjustable Amount Loans == Lower prices Adjustable fee loans ordinarily have lower costs than predetermined ones 宝贝价格

Fulleyqueuerm

2013年4月19日11:20 | /#14

回复 | 引用 This is really cool thanks for posting: 哈哈

Fulleyqueuerm

2013年4月19日13:24 | /#15

回复 | 引用 Start with your homework and program what it is you want to achieve payday loan. Give yourself the responsibility of dealing the best accessible secured financial loan online

The consumer must be aware of these changes and has the right to be well informed Unemployment can often be an option, nonetheless that from time to time takes time to start out receiving 宝贝价格

Fulleyqueuerm

2013年4月19日13:28 | /#16

回复 | 引用 As we discussed, there are ways to safeguard yourself via getting into debt you really wouldn’t like instant payday loans. It is therefore important to set realistic goals for your project finance investigating your own features first

To get your obtain accepted of those same day lending options one forced to meet the subsequent circumstances which have been : – you must become adult, you will need a reputable bank account, you should be at the present employed, you have to obtain monthly salary Each one incorporates its unique plus dissimilar features 宝贝价格

Fulleyqueuerm

2013年4月19日16:11 | /#17

回复 | 引用 It is usually pertaining to larger ranges, up to virtually the entire borrowing limit on the credit card payday loans. Because of their redundancy and less-than-perfect credit record, these types of peopleare unable to receive the money they gotta have in order to get an auto

Now with the net method you are able to apply for bank loan directly from at your house as there are lots of lender online providing financial loan at a diverse rate that can be done a proper research online and decided on a best deal by yourself you have populate an online application form with few detail with 24 time the loan request will be okayed and settled in your bill These loans turn out to be fruitful when you are supposed to complete some emergent requires 宝贝价格

Fulleyqueuerm

2013年4月19日16:48 | /#18

回复 | 引用 Even so secured loans feature lower interest rates than unsecured finance uk pay day loans. This isn’t entirely correct, as it offers some kind of reason

The fifth issue to ask in advance of spending money is Is there a product warranty Cash possesses risen for being king just as before as credit ratings is nowhere fast to be had as well as Dow cannot promise the particular returns it once did 宝贝价格

Fulleyqueuerm

2013年4月19日19:00 | /#19

回复 | 引用 Through consolidating obligations, you can watch the movements of your hard cash more handily and thoroughly payday loan. Precisely why the idea to generate money,have personal freedom is unattractive

Cash loans are believed to be as a fascinating loan solution as it enable you to access to the income without any publicity and difficulty Thus, there are many areas of curiosity on the Internet that provides extra money 宝贝价格

Fulleyqueuerm

2013年4月19日20:42 | /#20

回复 | 引用 2 government agencies, Work of the Comptroller with the Currency as well as the Office involving Thrift Supervision, started to concern joint stories containing an extensive picture of approximately 66% of the mortgages in the United States pay day loans. It could be also applied to provide workers his or her salary

Know What You’re Buying In picking your new rv, there are several things to take into consideration These loans are quite useful in dealing with the problems of individuals on credit ratings crisis 宝贝价格

Fulleyqueuerm

2013年4月19日20:56 | /#21

回复 | 引用 A few) Abuses in lending You will find a form of neglect in lender out financial products to borrowers which is known as Predatory loans’ pay day loans. Nearly everyone products proposal a particular quantity of unique location (2 to 4 on everyday) for each $ used up

Periodically, your note publication must be totalled with your standard bank statements In addition, a person required to send us any of your documents although applying with us 宝贝价格

Fulleyqueuerm

2013年4月19日23:20 | /#22

回复 | 引用 Ones structured settlement deal money would probably serve as a person’s retirement savings payday loans online. In a situation of any job decline one has to cave in all the components held by means of them caused by non-repayment of the mortgage loan

These financing options are also likely to be the most expensive This is certainly likely to be in which the individual is and so desperate and it has no choice that they are gonna accept whichever terms they are offered Individual debts are made up of associated with debt which includes mortgages, college loans, credit card debt, secured car loans and short term loans 宝贝价格

Fulleyqueuerm

2013年4月20日00:24 | /#23

回复 | 引用 Over the entire period with the agreement, these kinds of financial savings is actually a large amount byby itself payday loan. How to Post for you to Newsgroups — Directions — Step one) You do not need in order to re-type this entire correspondence to do your posting

As a result, loan officers often engage in predatory methods, particularly for sub-prime consumers The folks are taking one of those loans in a really increased rate and the banking institutions and other lender companies in addition to institutions show in their reviews that they are the favourite loans by the people these days 宝贝价格

Fulleyqueuerm

2013年4月20日02:37 | /#24

回复 | 引用 This will bring you in a whole lot worse trouble when compared with you started out there it pay day loan. Debt management ideas, debt consolidation, DRO etc can be of greater assist to you, in order to avoid chapter 7 and choose its easily affordable alternate options

The concept will depend on the idea that the house has a repaired value on the market today are dependent, for example, $ 250,000 Nevertheless, this is to become expected since loan themselves caters to subwoofer prime, higher-risk borrowers 宝贝价格

SewananiLiene

2013年4月21日23:35 | /#25

回复 | 引用 buy tramadol overnight cod where to buy tramadol – buy tramadol cod

Reitleageda

2013年4月24日10:15 | /#26

回复 | 引用 tramadol 50mg order tramadol – order tramadol online mastercard

odorkenna

2013年4月26日13:07 | /#27

回复 | 引用 buy tramadol180 buy tramadol cod online – where to buy tramadol online

Fulleyqueuerm

2013年5月2日17:37 | /#28

回复 | 引用 Along with secured personal cash loan the benefit is that you simply would get a better apr on your amount of the loan payday loans. The excuse is clear:It really is clear these particular individuals are great payers

You can inquire any amount you could reasonably afford the lender if you find yourself paid, by using commonly of course amounts about $3,000 For the reason that you have no power in reducing a loan

Fulleyqueuerm

2013年5月2日17:52 | /#29

回复 | 引用 Granted becoming fitter you co-sign a personal student loan for the child who may have not yet had the opportunity to establish the credit history, although as far as many people asking for this kind of favor within you, stand solid and say no payday loans uk. It can be demanding to be considering that every thirty days and it surely imposes limits to the price range

You wish to continue to purchase savings from your paycheck when you get paid at the same time The total cost of borrowing from the bank money goes beyond just basic interest rates

Fulleyqueuerm

2013年5月2日18:10 | /#30

回复 | 引用 Once 1 provides the loan provider with a evidence ownership, the other get loans which range from $5,500 to $75,Thousand depending on the price of ones property payday loans. They are machinery work and even the particular details participate in crucial component

Building your own merchant credit card for credit-based card processing and installing a shopping cart can potentially run into large sums of money Subprime lending products are commonly used for home loans, car financing, credit cards and private loans

GepSmedaWem

2013年5月5日16:24 | /#31

回复 | 引用 buy tramadol cod next day delivery generic tramadol online – buy tramadolwithout prescriptions

BusJeshymes

2013年5月8日10:08 | /#32

回复 | 引用 http://www.achildsplace.org/banners/tramadolonline//#2493 buy tramadolno prescription – tramadol online overnight

Fulleyqueuerm

2013年5月9日12:18 | /#33

回复 | 引用 The following decline in home based prices in addition led to home loan business the number of dollars outs, the news supply says pay day loans. Pawn brokers will give you credit in exchange for a private item worthwhile

Just for this kind of funding, the cash advance is perfect for a lot of, if only because of the speed of your reply A number of lenders demand as much as 31 pounds every 100 fat covered, however, if you purchased handle separately this can be as little as A couple of pounds 65 pence 宝贝价格

Fulleyqueuerm

2013年5月9日13:03 | /#34

回复 | 引用 Youve fulfilled your current side in the business offer, cut costs tothe bone fragments and approved these cost savings onto your clients in the form of incentivesand discount rates payday loans online direct lenders. Then, money will be relocated in couple of hours and you can have used them without any burden

By way of only a few private along with financial information and facts, it allows a probable consumer to immediately evaluate the fees and charges with diverse car financing Seeing that floating costs are rates that go up and down with adjustments in the prime amount 宝贝价格

Fulleyqueuerm

2013年5月10日02:26 | /#35

回复 | 引用 Unsecured loans are those financial products which are secured by investments with a cost that equals, or surpasses, the amount of the borrowed funds uk payday loans. Suppose you need fast cash enhance payday loan, you need to do what regarding responsibility with regard to repaying your debt

Enter in things like “avoid personal bankruptcy,” “credit unit card debt relief,In . and “debt settlement” while searching bar merely to get a sense of your options Depending on the availed account, term in order to reimbursement may vary more or less coming from 2 weeks so that you can 4 weeks 宝贝价格

Fulleyqueuerm

2013年5月10日02:46 | /#36

回复 | 引用 There are so many ways to save on your next vehicle instant loans. Consider the item or thing you want Is the idea absolutely necessary

Everybody is together a seller and a buyer The lenders that will help are going to be the internets special funding lenders 宝贝价格

Fulleyqueuerm

2013年5月10日15:10 | /#37

回复 | 引用 By using these previously mentioned discussed items, borrowers can certainly surely solve all their complications in a reduced period of time payday loans online. With the time period payments that will out of a structured settlement, it would be very difficult to obtain these tasks

The most prevalent reasons why persons apply for hel-home equity loans are with regard to debt consolidation, renovations and getaways The Arc Mortgage Program delivers interest free postponed loans which are repayable over a period which can be extended around five years 宝贝价格

Fulleyqueuerm

2013年5月10日15:53 | /#38

回复 | 引用 It is found that agreement businessmen relationship with the most effective hard cash lenders with an easy going instant online payday loans. Do not pity us – I know I’m going to be okay – However do have little stomach ache

On the web auto loan information mill available in a large number to let you understand the dream about owning a car at the best possible rate They give an opportunity for individuals create or even restore a favorable credit rating 宝贝价格

Fulleyqueuerm

2013年5月10日16:40 | /#39

回复 | 引用 Most people as a mortgage lender are minimum interested in your own past credit score records payday loans. (The balloon particular date is the particular date that the whole balance on the loan comes due, regardless of if the loan is definitely amortized or not)

Tips 3: Quickly Earn income in Nana Turismo 5 So as to earn more money in Gran Turismo Several, you must possess a fast car or truck and continue the test observe on Ohydrates and every a couple of laps you’ll earn A hundred and fifty,000CR As it’s an unsecured loan, you don’t have of a guarantee 宝贝价格

Sibomivottmed

2013年5月14日13:36 | /#40

回复 | 引用 buy misoprostol online ireland – buy misoprostol online no prescription – where can i buy cytotec philippines

Sibomivottmed

2013年5月14日20:13 | /#41

回复 | 引用 buy cytotec forum – buy cytotec canada – buy generic cytotec online

SyncSibbozy

2013年5月15日11:41 | /#42

回复 | 引用 Buy Cytotec Online – buy cytotec and mifeprex – buy cytotec manila

Wenidremn

2013年5月17日16:53 | /#43

回复 | 引用 tramadol online overnight buy tramadol onlinereviews – buy tramadol overnight shipping

Wenidremn

2013年5月18日02:20 | /#44

回复 | 引用 buy tramadol cod online tramadol no prescription – buy tramadoltablets

payday loans quick cash

2013年5月20日01:42 | /#45

回复 | 引用 Just inspected my gain today by using Credit Professional and it is 778 – a record illustrious quick payday loans. The type of technique used will certainly differ from business to business making this very puzzling for some staff members

For availing these loans, you should have permanent job for a lot more than 5 many months Thus, it can be advised to implement the moisture infused style, as the water present in your powder can moisturize your sensitive skin 宝贝价格

Brimagoag

2013年5月20日19:05 | /#46

回复 | 引用 Buy Tramadol Online order tramadol online mastercard – buy tramadol cod

brearsesliple

2013年5月28日22:21 | /#47

回复 | 引用 buy ambien tijuana ambien order canada – how to buy ambien

brearsesliple

2013年5月29日05:30 | /#48

回复 | 引用 order ambien cr buy ambien online fast shipping – buy ambien 12.5 mg

WhaskleleHoks

2013年6月5日14:46 | /#49

回复 | 引用 buy generic tramadol online buy tramadolwithout prescriptions – order tramadol online without prescription

WhaskleleHoks

2013年6月6日00:17 | /#50

回复 | 引用 Buy Tramadol Online tramadol generic – buy tramadol without prescriptions

Lerocrill

2013年7月14日02:37 | /#51

回复 | 引用 Lululemon Outlet I enjoy what you guys are usually up too. This sort of clever work and reporting! Keep up the amazing works guys I’ve included you guys to our blogroll.

wowdWEmPBv

2013年8月4日07:03 | /#52

回复 | 引用 read more buying tramadol online reviews – tramadol dosage human

gChDfimcvC

2013年8月6日05:28 | /#53

回复 | 引用 order tramadol no prescription buy tramadol egypt – tramadol hcl 500mg

wTVouVPNkh

2013年8月11日13:35 | /#54

回复 | 引用 Go Here tramadol withdrawal while pregnant – buy tramadol using mastercard

kLHJQjRvZY

2013年8月11日15:34 | /#55

回复 | 引用 buy tramadol online us pharmacy no prescription tramadol – tramadol withdrawal method

CUBSRckWgu

2013年8月11日15:57 | /#56

回复 | 引用 http://worldfineart.com/online/tramadol/ tramadol addiction detox – buy tramadol health solutions network

CUmMRFVgzh

2013年8月11日16:28 | /#57

回复 | 引用 buy valium online long will 10mg valium last – buy valium uk 2012

ZjWBhamqoS

2013年8月11日17:03 | /#58

回复 | 引用 http://cooperembloc.udg.edu/wp-content/buytramadol//#3681 tramadol no prescription pharmacy – tramadol normal dosage

MpcdpTHqzY

2013年8月11日17:59 | /#59

回复 | 引用 generic adderall online adderall online prescription no membership – adderall xr abuse potential

udCphSccnE

2013年8月11日18:47 | /#60

回复 | 引用 buy adderall max adderall dosage 24 hours – vitamins help adderall withdrawal

JLSWnGDXai

2013年8月11日19:25 | /#61

回复 | 引用 http://aviation-history.com/aip/buytramadol//#34571 side effects of ultram tramadol – what is tramadol ultram 50 mg

VedCaLASdE

2013年8月11日19:47 | /#62

回复 | 引用 buy tramadol online buy tramadol c.o.d saturday delivery – generic tramadol er

QmQQvgBHyL

2013年8月11日20:26 | /#63

回复 | 引用 buy valium online valium dosage 10mg – what is a valium pill for

LhcDligQyE

2013年8月11日22:14 | /#64

回复 | 引用 buy tramadol buy tramadol cod overnight delivery – good place buy tramadol online

qvWPvbVdOv

2013年8月11日23:37 | /#65

回复 | 引用 http://worldfineart.com/online/tramadol/ where to buy tramadol forum – tramadol get high off

IZiBjHUJTq

2013年8月12日01:17 | /#66

回复 | 引用 this link buy adderall online from usa – buy adderall online no prescription membership

WuOBgMxOzv

2013年8月12日01:47 | /#67

回复 | 引用 what is adderall adderall side effects uti – adderall abuse drug test

gVoGNeJxLo

2013年8月12日04:24 | /#68

回复 | 引用 buy valium valium lyrics – buy valium bali

kfwGtwxOdM

2013年8月12日05:56 | /#69

回复 | 引用 tramadol 50mg tramadol hcl 50 mg get you high – buy tramadol online overnight

KkEDjasVnX

2013年8月12日20:25 | /#70

回复 | 引用 download adderall shortage – adderall xr side effects long term

yukDPlqiXX

2013年8月12日20:46 | /#71

回复 | 引用 buy tramadol tramadol hcl or tramadol – tramadol 50mg value

kqqvmykczx

2013年8月12日23:13 | /#72

回复 | 引用 xanax online buy xanax online 2mg – side effects of 1mg xanax 昵称 (必填)

电子邮箱 (我们会为您保密) (必填) 网址

订阅评论

验证图片

刷新验证码

验证码 /* 深入浅出 Java Concurrency javacc lookahead 教程

订阅

搜索:

标签

cache Cassandra Concurrent Django Dynamo event google HBase http io ipad java javacc JBoss jvm linux lucene MapReduce mongodb mysql nio nosql python redis RFS Scala Siege spark SSD TokyoCabine TokyoTyrant Voldemort 分布式 多线程 实时 实时计算 并发 招聘 架构 测试 海量数据 消息队列 源码分析 爬虫 高性能

分类目录

近期评论

热门文章

我关注的

我还在

Meta

回到顶部 WordPress

版权所有 © 2010-2013 yiihsia[互联网后端技术] 主题由 NeoEase 提供, 通过 XHTML 1.1CSS 3 验证.

HttpUrlConnection底层实现和关于java host绑定ip即时生效的设置及分析

Posted on

HttpUrlConnection底层实现和关于java host绑定ip即时生效的设置及分析

程序员之路
  1. 最近有个需求需要对于获取URL页面进行host绑定并且立即生效,在java里面实现可以用代理服务器来实现:因为在测试环境下可能需要通过绑定来访问测试环境的应用
  2. 实现代码如下:
  3. public static String getResponseText(String queryUrl,String host,String ip) { //queryUrl,完整的url,host和ip需要绑定的host和ip
  4. InputStream is = null;
  5. BufferedReader br = null;
  6. StringBuffer res = new StringBuffer();
  7. try {
  8. HttpURLConnection httpUrlConn = null;
  9. URL url = new URL(queryUrl);
  10. if(ip!=null){
  11. String str[] = ip.split("\.");
  12. byte[] b =new byte[str.length];
  13. for(int i=0,len=str.length;i<len;i++){
  14. b[i] = (byte)(Integer.parseInt(str[i],10));
  15. }
  16. Proxy proxy = new Proxy(Proxy.Type.HTTP,
  17. new InetSocketAddress(InetAddress.getByAddress(b), 80)); //b是绑定的ip,生成proxy代理对象,因为http底层是socket实现,
  18. httpUrlConn = (HttpURLConnection) url
  19. .openConnection(proxy);
  20. }else{
  21. httpUrlConn = (HttpURLConnection) url
  22. .openConnection();
  23. }
  24. httpUrlConn.setRequestMethod("GET");
  25. httpUrlConn.setDoOutput(true);
  26. httpUrlConn.setConnectTimeout(2000);
  27. httpUrlConn.setReadTimeout(2000);
  28. httpUrlConn.setDefaultUseCaches(false);
  29. httpUrlConn.setUseCaches(false);
  30. is = httpUrlConn.getInputStream();
  31. 那么底层对于proxy对象到底是怎么处理,底层的socket实现到底怎么样,带着这个疑惑看了下jdk的rt.jar对于这块的处理
  32. httpUrlConn = (HttpURLConnection) url.openConnection(proxy)
  33. java.net.URL类里面的openConnection方法:
  34. public URLConnection openConnection(Proxy proxy){
  35. return handler.openConnection(this, proxy); Handler是sun.net.www.protocol.http.Handler.java类,继承java.net. URLStreamHandler.java类,用来处理http连接请求响应的。
  36. }
  37. Handler的方法:
  38. protected java.net.URLConnection openConnection(URL u, Proxy p)
  39. throws IOException {
  40. return new HttpURLConnection(u, p, this);
  41. }
  42. 只是简单的生成sun.net.www.protocl.http.HttpURLConnection对象,并进行初始化
  43. protected HttpURLConnection(URL u, Proxy p, Handler handler) {
  44. super(u);
  45. requests = new MessageHeader(); 请求头信息生成类
  46. responses = new MessageHeader(); 响应头信息解析类
  47. this.handler = handler;
  48. instProxy = p; 代理服务器对象
  49. cookieHandler = (CookieHandler)java.security.AccessController.doPrivileged(
  50. new java.security.PrivilegedAction() {
  51. public Object run() {
  52. return CookieHandler.getDefault();
  53. }
  54. });
  55. cacheHandler = (ResponseCache)java.security.AccessController.doPrivileged(
  56. new java.security.PrivilegedAction() {
  57. public Object run() {
  58. return ResponseCache.getDefault();
  59. }
  60. });
  61. }
  62. 最终在httpUrlConn.getInputStream();才进行socket连接,发送http请求,解析http响应信息。具体过程如下:
  63. sun.net.www.protocl.http.HttpURLConnection.java的getInputStream方法:
  64. public synchronized InputStream getInputStream() throws IOException {
  65. ...socket连接
  66. connect();
  67. ...
  68. ps = (PrintStream)http.getOutputStream(); 获得输出流,打开连接之后已经生成。
  69. if (!streaming()) {
  70. writeRequests(); 输出http请求头信息
  71. }
  72. ...
  73. http.parseHTTP(responses, pi, this); 解析响应信息
  74. if(logger.isLoggable(Level.FINEST)) {
  75. logger.fine(responses.toString());
  76. }
  77. inputStream = http.getInputStream(); 获得输入流
  78. }
  79. 其中connect()调用方法链:
  80. plainConnect(){
  81. ...
  82. Proxy p = null;
  83. if (sel != null) {
  84. URI uri = sun.net.www.ParseUtil.toURI(url);
  85. Iterator it = sel.select(uri).iterator();
  86. while (it.hasNext()) {
  87. p = it.next();
  88. try {
  89. if (!failedOnce) {
  90. http = getNewHttpClient(url, p, connectTimeout);
  91. ...
  92. }
  93. getNewHttpClient(){
  94. ...
  95. return HttpClient.New(url, p, connectTimeout, useCache);
  96. ...
  97. }
  98. 下面跟进去最终建立socket连接的代码:
  99. sun.net.www.http.HttpClient.java的openServer()方法建立socket连接:
  100. protected synchronized void openServer() throws IOException {
  101. ...
  102. if ((proxy != null) && (proxy.type() == Proxy.Type.HTTP)) {
  103. sun.net.www.URLConnection.setProxiedHost(host);
  104. if (security != null) {
  105. security.checkConnect(host, port);
  106. }
  107. privilegedOpenServer((InetSocketAddress) proxy.address());最终socket连接的是设置的代理服务器的地址,
  108. ...
  109. }
  110. private synchronized void privilegedOpenServer(final InetSocketAddress server)
  111. throws IOException
  112. {
  113. try {
  114. java.security.AccessController.doPrivileged(
  115. new java.security.PrivilegedExceptionAction() {
  116. public Object run() throws IOException {
  117. openServer(server.getHostName(), server.getPort()); 注意openserver函数 这里的server的getHostName是设置的代理服务器,(ip或者hostname,如果是host绑定设置的代理服务器的ip,那么这里getHostName出来的就是ip地址,可以去查看InetSocketAddress类的getHostName方法)
  118. return null;
  119. }
  120. });
  121. } catch (java.security.PrivilegedActionException pae) {
  122. throw (IOException) pae.getException();
  123. }
  124. }
  125. public void openServer(String server, int port) throws IOException {
  126. serverSocket = doConnect(server, port); 生成的Socket连接对象
  127. try {
  128. serverOutput = new PrintStream(
  129. new BufferedOutputStream(serverSocket.getOutputStream()),
  130. false, encoding); 生成输出流,
  131. } catch (UnsupportedEncodingException e) {
  132. throw new InternalError(encoding+" encoding not found");
  133. }
  134. serverSocket.setTcpNoDelay(true);
  135. }
  136. protected Socket doConnect (String server, int port)
  137. throws IOException, UnknownHostException {
  138. Socket s;
  139. if (proxy != null) {
  140. if (proxy.type() == Proxy.Type.SOCKS) {
  141. s = (Socket) AccessController.doPrivileged(
  142. new PrivilegedAction() {
  143. public Object run() {
  144. return new Socket(proxy);
  145. }});
  146. } else
  147. s = new Socket(Proxy.NO_PROXY);
  148. } else
  149. s = new Socket();
  150. // Instance specific timeouts do have priority, that means
  151. // connectTimeout & readTimeout (-1 means not set)
  152. // Then global default timeouts
  153. // Then no timeout.
  154. if (connectTimeout >= 0) {
  155. s.connect(new InetSocketAddress(server, port), connectTimeout);
  156. } else {
  157. if (defaultConnectTimeout > 0) {
  158. s.connect(new InetSocketAddress(server, port), defaultConnectTimeout);//连接到代理服务器,看下面Socket类的connect方法代码
  159. } else {
  160. s.connect(new InetSocketAddress(server, port));
  161. }
  162. }
  163. if (readTimeout >= 0)
  164. s.setSoTimeout(readTimeout);
  165. else if (defaultSoTimeout > 0) {
  166. s.setSoTimeout(defaultSoTimeout);
  167. }
  168. return s;
  169. }
  170. 上面的new InetSocketAddress(server, port)这里会涉及到java DNS cache的处理,
  171. public InetSocketAddress(String hostname, int port) {
  172. if (port < 0 || port > 0xFFFF) {
  173. throw new IllegalArgumentException("port out of range:" + port);
  174. }
  175. if (hostname == null) {
  176. throw new IllegalArgumentException("hostname can't be null");
  177. }
  178. try {
  179. addr = InetAddress.getByName(hostname); //这里会有java DNS缓存的处理,先从缓存取hostname绑定的ip地址,如果取不到再通过OS的DNS cache机制去取,取不到再从DNS服务器上取。
  180. } catch(UnknownHostException e) {
  181. this.hostname = hostname;
  182. addr = null;
  183. }
  184. this.port = port;
  185. }
  186. 当然最终的Socket.java的connect方法
  187. java.net.socket
  188. public void connect(SocketAddress endpoint, int timeout) throws IOException {
  189. if (endpoint == null)
  190. if (timeout < 0)
  191. throw new IllegalArgumentException("connect: timeout can't be negative");
  192. if (isClosed())
  193. throw new SocketException("Socket is closed");
  194. if (!oldImpl && isConnected())
  195. throw new SocketException("already connected");
  196. if (!(endpoint instanceof InetSocketAddress))
  197. throw new IllegalArgumentException("Unsupported address type");
  198. InetSocketAddress epoint = (InetSocketAddress) endpoint;
  199. SecurityManager security = System.getSecurityManager();
  200. if (security != null) {
  201. if (epoint.isUnresolved())
  202. security.checkConnect(epoint.getHostName(),
  203. epoint.getPort());
  204. else
  205. security.checkConnect(epoint.getAddress().getHostAddress(),
  206. epoint.getPort());
  207. }
  208. if (!created)
  209. createImpl(true);
  210. if (!oldImpl)
  211. impl.connect(epoint, timeout);
  212. else if (timeout == 0) {
  213. if (epoint.isUnresolved()) //如果没有设置SocketAddress的ip地址,则用域名去访问
  214. impl.connect(epoint.getAddress().getHostName(),
  215. epoint.getPort());
  216. else
  217. impl.connect(epoint.getAddress(), epoint.getPort()); 最终socket连接的是设置的SocketAddress的ip地址,
  218. } else
  219. throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
  220. connected = true;
  221. //*
  222. /* If the socket was not bound before the connect, it is now because
  223. /* the kernel will have picked an ephemeral port & a local address
  224. /*/
  225. bound = true;
  226. }
  227. 我们再看下通过socket来发送HTTP请求的处理代码,也就是sun.net.www.protocl.http.HttpURLConnection.java的getInputStream方法中调用的writeRequests()方法:
  228. private void writeRequests() throws IOException { 这段代码就是封装http请求的头请求信息,通过socket发送出去
  229. //* print all message headers in the MessageHeader
  230. /* onto the wire - all the ones we've set and any
  231. /* others that have been set
  232. /*/
  233. // send any pre-emptive authentication
  234. if (http.usingProxy) {
  235. setPreemptiveProxyAuthentication(requests);
  236. }
  237. if (!setRequests) {
  238. //* We're very particular about the order in which we
  239. /* set the request headers here. The order should not
  240. /* matter, but some careless CGI programs have been
  241. /* written to expect a very particular order of the
  242. /* standard headers. To name names, the order in which
  243. / Navigator3.0 sends them. In particular, we make /sure/*
  244. /* to send Content-type: <> and Content-length:<> second
  245. /* to last and last, respectively, in the case of a POST
  246. /* request.
  247. /*/
  248. if (!failedOnce)
  249. requests.prepend(method + " " + http.getURLFile()+" " +
  250. httpVersion, null);
  251. if (!getUseCaches()) {
  252. requests.setIfNotSet ("Cache-Control", "no-cache");
  253. requests.setIfNotSet ("Pragma", "no-cache");
  254. }
  255. requests.setIfNotSet("User-Agent", userAgent);
  256. int port = url.getPort();
  257. String host = url.getHost();
  258. if (port != -1 && port != url.getDefaultPort()) {
  259. host += ":" + String.valueOf(port);
  260. }
  261. requests.setIfNotSet("Host", host);
  262. requests.setIfNotSet("Accept", acceptString);
  263. //*
  264. /* For HTTP/1.1 the default behavior is to keep connections alive.
  265. /* However, we may be talking to a 1.0 server so we should set
  266. /* keep-alive just in case, except if we have encountered an error
  267. /* or if keep alive is disabled via a system property
  268. /*/
  269. // Try keep-alive only on first attempt
  270. if (!failedOnce && http.getHttpKeepAliveSet()) {
  271. if (http.usingProxy) {
  272. requests.setIfNotSet("Proxy-Connection", "keep-alive");
  273. } else {
  274. requests.setIfNotSet("Connection", "keep-alive");
  275. }
  276. } else {
  277. //*
  278. /* RFC 2616 HTTP/1.1 section 14.10 says:
  279. /* HTTP/1.1 applications that do not support persistent
  280. /* connections MUST include the "close" connection option
  281. /* in every message
  282. /*/
  283. requests.setIfNotSet("Connection", "close");
  284. }
  285. // Set modified since if necessary
  286. long modTime = getIfModifiedSince();
  287. if (modTime != 0 ) {
  288. Date date = new Date(modTime);
  289. //use the preferred date format according to RFC 2068(HTTP1.1),
  290. // RFC 822 and RFC 1123
  291. SimpleDateFormat fo =
  292. new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
  293. fo.setTimeZone(TimeZone.getTimeZone("GMT"));
  294. requests.setIfNotSet("If-Modified-Since", fo.format(date));
  295. }
  296. // check for preemptive authorization
  297. AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url);
  298. if (sauth != null && sauth.supportsPreemptiveAuthorization() ) {
  299. // Sets "Authorization"
  300. requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method));
  301. currentServerCredentials = sauth;
  302. }
  303. if (!method.equals("PUT") && (poster != null || streaming())) {
  304. requests.setIfNotSet ("Content-type",
  305. "application/x-www-form-urlencoded");
  306. }
  307. if (streaming()) {
  308. if (chunkLength != -1) {
  309. requests.set ("Transfer-Encoding", "chunked");
  310. } else {
  311. requests.set ("Content-Length", String.valueOf(fixedContentLength));
  312. }
  313. } else if (poster != null) {
  314. // add Content-Length & POST/PUT data //
  315. synchronized (poster) {
  316. // close it, so no more data can be added //
  317. poster.close();
  318. requests.set("Content-Length",
  319. String.valueOf(poster.size()));
  320. }
  321. }
  322. // get applicable cookies based on the uri and request headers
  323. // add them to the existing request headers
  324. setCookieHeader();
  325. }
  326. 再来看看把socket响应信息解析为http的响应信息的代码:
  327. sun.net.www.http.HttpClient.java的parseHTTP方法:
  328. private boolean parseHTTPHeader(MessageHeader responses, ProgressSource pi, HttpURLConnection httpuc)
  329. throws IOException {
  330. // If "HTTP//" is found in the beginning, return true. Let
  331. /* HttpURLConnection parse the mime header itself.
  332. /*
  333. /* If this isn't valid HTTP, then we don't try to parse a header
  334. /* out of the beginning of the response into the responses,
  335. /* and instead just queue up the output stream to it's very beginning.
  336. /* This seems most reasonable, and is what the NN browser does.
  337. /*/
  338. keepAliveConnections = -1;
  339. keepAliveTimeout = 0;
  340. boolean ret = false;
  341. byte[] b = new byte[8];
  342. try {
  343. int nread = 0;
  344. serverInput.mark(10);
  345. while (nread < 8) {
  346. int r = serverInput.read(b, nread, 8 - nread);
  347. if (r < 0) {
  348. break;
  349. }
  350. nread += r;
  351. }
  352. String keep=null;
  353. ret = b[0] == 'H' && b[1] == 'T'
  354. && b[2] == 'T' && b[3] == 'P' && b[4] == '/' &&
  355. b[5] == '1' && b[6] == '.';
  356. serverInput.reset();
  357. if (ret) { // is valid HTTP - response started w/ "HTTP/1."
  358. responses.parseHeader(serverInput);
  359. // we've finished parsing http headers
  360. // check if there are any applicable cookies to set (in cache)
  361. if (cookieHandler != null) {
  362. URI uri = ParseUtil.toURI(url);
  363. // NOTE: That cast from Map shouldn't be necessary but
  364. // a bug in javac is triggered under certain circumstances
  365. // So we do put the cast in as a workaround until
  366. // it is resolved.
  367. if (uri != null)
  368. cookieHandler.put(uri, (Map>)responses.getHeaders());
  369. }
  370. //* decide if we're keeping alive:
  371. /* This is a bit tricky. There's a spec, but most current
  372. /* servers (10/1/96) that support this differ in dialects.
  373. /* If the server/client misunderstand each other, the
  374. /* protocol should fall back onto HTTP/1.0, no keep-alive.
  375. /*/
  376. if (usingProxy) { // not likely a proxy will return this
  377. keep = responses.findValue("Proxy-Connection");
  378. }
  379. if (keep == null) {
  380. keep = responses.findValue("Connection");
  381. }
  382. if (keep != null && keep.toLowerCase().equals("keep-alive")) {
  383. //* some servers, notably Apache1.1, send something like:
  384. /* "Keep-Alive: timeout=15, max=1" which we should respect.
  385. /*/
  386. HeaderParser p = new HeaderParser(
  387. responses.findValue("Keep-Alive"));
  388. if (p != null) {
  389. // default should be larger in case of proxy //
  390. keepAliveConnections = p.findInt("max", usingProxy?50:5);
  391. keepAliveTimeout = p.findInt("timeout", usingProxy?60:5);
  392. }
  393. } else if (b[7] != '0') {
  394. //*
  395. /* We're talking 1.1 or later. Keep persistent until
  396. /* the server says to close.
  397. /*/
  398. if (keep != null) {
  399. //*
  400. /* The only Connection token we understand is close.
  401. /* Paranoia: if there is any Connection header then
  402. /* treat as non-persistent.
  403. /*/
  404. keepAliveConnections = 1;
  405. } else {
  406. keepAliveConnections = 5;
  407. }
  408. }
  409. ……
  410. }
  411. 对于java.net包的http,ftp等各种协议的底层实现,可以参考rt.jar下面的几个包的代码:
  412. sun.net.www.protocl下的几个包。
  413. 在http client中也可以设置代理:
  414. HostConfiguration conf = new HostConfiguration();
  415. conf.setHost(host);
  416. conf.setProxy(ip, 80);
  417. statusCode = httpclient.executeMethod(conf,getMethod);
  418. httpclient自己也是基于socket封装的http处理的库。底层代理的实现是一样的。
  419. 另外一种不设置代理,通过反射修改InetAddress的cache也是ok的。但是这种方法非常不推荐,不要使用,因为对于proxy代理服务器概念了解不清楚,最开始还使用这种方法,
  420. public static void jdkDnsNoCache(final String host, final String ip)
  421. throws SecurityException, NoSuchFieldException,
  422. IllegalArgumentException, IllegalAccessException {
  423. if (StringUtils.isBlank(host)) {
  424. return;
  425. }
  426. final Class clazz = java.net.InetAddress.class;
  427. final Field cacheField = clazz.getDeclaredField("addressCache");
  428. cacheField.setAccessible(true);
  429. final Object o = cacheField.get(clazz);
  430. Class clazz2 = o.getClass();
  431. final Field cacheMapField = clazz2.getDeclaredField("cache");
  432. cacheMapField.setAccessible(true);
  433. final Map cacheMap = (Map) cacheMapField.get(o);
  434. AccessController.doPrivileged(new PrivilegedAction() {
  435. public Object run() {
  436. try {
  437. synchronized (o) {// 同步是必须的,因为o可能会有多个线程同时访问修改。
  438. // cacheMap.clear();//这步比较关键,用于清除原来的缓存
  439. // cacheMap.remove(host);
  440. if (!StringUtils.isBlank(ip)) {
  441. InetAddress inet = InetAddress.getByAddress(host,IPUtil.int2byte(ip));
  442. InetAddress addressstart = InetAddress.getByName(host);
  443. Object cacheEntry = cacheMap.get(host);
  444. cacheMap.put(host,newCacheEntry(inet,cacheEntry));
  445. // cacheMap.put(host,newCacheEntry(newInetAddress(host, ip)));
  446. }else{
  447. cacheMap.remove(host);
  448. }
  449. // System.out.println(getStaticProperty(
  450. // "java.net.InetAddress", "addressCacheInit"));
  451. // System.out.println(invokeStaticMethod("java.net.InetAddress","getCachedAddress",new
  452. // Object[]{host}));
  453. }
  454. } catch (Throwable te) {
  455. throw new RuntimeException(te);
  456. }
  457. return null;
  458. }
  459. });
  460. final Map cacheMapafter = (Map) cacheMapField.get(o);
  461. System.out.println(cacheMapafter);
  462. }
  463. 关于java中对于DNS的缓存设置可以参考:
  464. 1.在${java_home}/jre/lib/secuiry/java.secuiry文件,修改下面为
  465. networkaddress.cache.negative.ttl=0 DNS解析不成功的缓存时间
  466. networkaddress.cache.ttl=0 DNS解析成功的缓存的时间
  467. 2.jvm启动时增加下面两个启动环境变量
  468. -Dsun.net.inetaddr.ttl=0
  469. -Dsun.net.inetaddr.negative.ttl=0
  470. 如果在java程序中使用,可以这么设置设置:
  471. java.security.Security.setProperty("networkaddress.cache.ttl" , "0");
  472. java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");
  473. 还有几篇文档链接可以查看:
  474. http://www.rgagnon.com/javadetails/java-0445.html
  475. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6247501
  476. linux下关于OS DNS设置的几个文件是
  477. /etc/resolve.conf
  478. /etc/nscd.conf
  479. /etc/nsswitch.conf
  480. http://www.linuxfly.org/post/543/
  481. http://linux.die.net/man/5/nscd.conf
  482. http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch18_:_Configuring_DNS
  483. http://linux.die.net/man/5/nscd.conf
    最近有个需求需要对于获取URL页面进行host绑定并且立即生效,在java里面实现可以用代理服务器来实现:因为在测试环境下可能需要通过绑定来访问测试环境的应用 实现代码如下: public static String getResponseText(String queryUrl,String host,String ip) { //queryUrl,完整的url,host和ip需要绑定的host和ip InputStream is = null; BufferedReader br = null; StringBuffer res = new StringBuffer(); try { HttpURLConnection httpUrlConn = null; URL url = new URL(queryUrl); if(ip!=null){ String str[] = ip.split("\."); byte[] b =new byte[str.length]; for(int i=0,len=str.length;i it = sel.select(uri).iterator(); while (it.hasNext()) { p = it.next(); try { if (!failedOnce) { http = getNewHttpClient(url, p, connectTimeout); ... } getNewHttpClient(){ ... return HttpClient.New(url, p, connectTimeout, useCache); ... } 下面跟进去最终建立socket连接的代码: sun.net.www.http.HttpClient.java的openServer()方法建立socket连接: protected synchronized void openServer() throws IOException { ... if ((proxy != null) && (proxy.type() == Proxy.Type.HTTP)) { sun.net.www.URLConnection.setProxiedHost(host); if (security != null) { security.checkConnect(host, port); } privilegedOpenServer((InetSocketAddress) proxy.address());最终socket连接的是设置的代理服务器的地址, ... } private synchronized void privilegedOpenServer(final InetSocketAddress server) throws IOException { try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction() { public Object run() throws IOException { openServer(server.getHostName(), server.getPort()); 注意openserver函数 这里的server的getHostName是设置的代理服务器,(ip或者hostname,如果是host绑定设置的代理服务器的ip,那么这里getHostName出来的就是ip地址,可以去查看InetSocketAddress类的getHostName方法) return null; } }); } catch (java.security.PrivilegedActionException pae) { throw (IOException) pae.getException(); } } public void openServer(String server, int port) throws IOException { serverSocket = doConnect(server, port); 生成的Socket连接对象 try { serverOutput = new PrintStream( new BufferedOutputStream(serverSocket.getOutputStream()), false, encoding); 生成输出流, } catch (UnsupportedEncodingException e) { throw new InternalError(encoding+" encoding not found"); } serverSocket.setTcpNoDelay(true); } protected Socket doConnect (String server, int port) throws IOException, UnknownHostException { Socket s; if (proxy != null) { if (proxy.type() == Proxy.Type.SOCKS) { s = (Socket) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return new Socket(proxy); }}); } else s = new Socket(Proxy.NOPROXY); } else s = new Socket(); // Instance specific timeouts do have priority, that means // connectTimeout & readTimeout (-1 means not set) // Then global default timeouts // Then no timeout. if (connectTimeout >= 0) { s.connect(new InetSocketAddress(server, port), connectTimeout); } else { if (defaultConnectTimeout > 0) { s.connect(new InetSocketAddress(server, port), defaultConnectTimeout);//连接到代理服务器,看下面Socket类的connect方法代码 } else { s.connect(new InetSocketAddress(server, port)); } } if (readTimeout >= 0) s.setSoTimeout(readTimeout); else if (defaultSoTimeout > 0) { s.setSoTimeout(defaultSoTimeout); } return s; } 上面的new InetSocketAddress(server, port)这里会涉及到java DNS cache的处理, public InetSocketAddress(String hostname, int port) { if (port < 0 || port > 0xFFFF) { throw new IllegalArgumentException("port out of range:" + port); } if (hostname == null) { throw new IllegalArgumentException("hostname can't be null"); } try { addr = InetAddress.getByName(hostname); //这里会有java DNS缓存的处理,先从缓存取hostname绑定的ip地址,如果取不到再通过OS的DNS cache机制去取,取不到再从DNS服务器上取。 } catch(UnknownHostException e) { this.hostname = hostname; addr = null; } this.port = port; } 当然最终的Socket.java的connect方法 java.net.socket public void connect(SocketAddress endpoint, int timeout) throws IOException { if (endpoint == null) if (timeout < 0) throw new IllegalArgumentException("connect: timeout can't be negative"); if (isClosed()) throw new SocketException("Socket is closed"); if (!oldImpl && isConnected()) throw new SocketException("already connected"); if (!(endpoint instanceof InetSocketAddress)) throw new IllegalArgumentException("Unsupported address type"); InetSocketAddress epoint = (InetSocketAddress) endpoint; SecurityManager security = System.getSecurityManager(); if (security != null) { if (epoint.isUnresolved()) security.checkConnect(epoint.getHostName(), epoint.getPort()); else security.checkConnect(epoint.getAddress().getHostAddress(), epoint.getPort()); } if (!created) createImpl(true); if (!oldImpl) impl.connect(epoint, timeout); else if (timeout == 0) { if (epoint.isUnresolved()) //如果没有设置SocketAddress的ip地址,则用域名去访问 impl.connect(epoint.getAddress().getHostName(), epoint.getPort()); else impl.connect(epoint.getAddress(), epoint.getPort()); 最终socket连接的是设置的SocketAddress的ip地址, } else throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)"); connected = true; // / If the socket was not bound before the connect, it is now because / the kernel will have picked an ephemeral port & a local address // bound = true; } 我们再看下通过socket来发送HTTP请求的处理代码,也就是sun.net.www.protocl.http.HttpURLConnection.java的getInputStream方法中调用的writeRequests()方法: private void writeRequests() throws IOException { 这段代码就是封装http请求的头请求信息,通过socket发送出去 // print all message headers in the MessageHeader / onto the wire - all the ones we've set and any / others that have been set // // send any pre-emptive authentication if (http.usingProxy) { setPreemptiveProxyAuthentication(requests); } if (!setRequests) { // We're very particular about the order in which we / set the request headers here. The order should not / matter, but some careless CGI programs have been / written to expect a very particular order of the / standard headers. To name names, the order in which / Navigator3.0 sends them. In particular, we make /sure/ / to send Content-type: <> and Content-length:<> second / to last and last, respectively, in the case of a POST / request. // if (!failedOnce) requests.prepend(method + " " + http.getURLFile()+" " + httpVersion, null); if (!getUseCaches()) { requests.setIfNotSet ("Cache-Control", "no-cache"); requests.setIfNotSet ("Pragma", "no-cache"); } requests.setIfNotSet("User-Agent", userAgent); int port = url.getPort(); String host = url.getHost(); if (port != -1 && port != url.getDefaultPort()) { host += ":" + String.valueOf(port); } requests.setIfNotSet("Host", host); requests.setIfNotSet("Accept", acceptString); // / For HTTP/1.1 the default behavior is to keep connections alive. / However, we may be talking to a 1.0 server so we should set / keep-alive just in case, except if we have encountered an error / or if keep alive is disabled via a system property // // Try keep-alive only on first attempt if (!failedOnce && http.getHttpKeepAliveSet()) { if (http.usingProxy) { requests.setIfNotSet("Proxy-Connection", "keep-alive"); } else { requests.setIfNotSet("Connection", "keep-alive"); } } else { // / RFC 2616 HTTP/1.1 section 14.10 says: / HTTP/1.1 applications that do not support persistent / connections MUST include the "close" connection option / in every message // requests.setIfNotSet("Connection", "close"); } // Set modified since if necessary long modTime = getIfModifiedSince(); if (modTime != 0 ) { Date date = new Date(modTime); //use the preferred date format according to RFC 2068(HTTP1.1), // RFC 822 and RFC 1123 SimpleDateFormat fo = new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); fo.setTimeZone(TimeZone.getTimeZone("GMT")); requests.setIfNotSet("If-Modified-Since", fo.format(date)); } // check for preemptive authorization AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url); if (sauth != null && sauth.supportsPreemptiveAuthorization() ) { // Sets "Authorization" requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method)); currentServerCredentials = sauth; } if (!method.equals("PUT") && (poster != null || streaming())) { requests.setIfNotSet ("Content-type", "application/x-www-form-urlencoded"); } if (streaming()) { if (chunkLength != -1) { requests.set ("Transfer-Encoding", "chunked"); } else { requests.set ("Content-Length", String.valueOf(fixedContentLength)); } } else if (poster != null) { // add Content-Length & POST/PUT data // synchronized (poster) { // close it, so no more data can be added // poster.close(); requests.set("Content-Length", String.valueOf(poster.size())); } } // get applicable cookies based on the uri and request headers // add them to the existing request headers setCookieHeader(); … } 再来看看把socket响应信息解析为http的响应信息的代码: sun.net.www.http.HttpClient.java的parseHTTP方法: private boolean parseHTTPHeader(MessageHeader responses, ProgressSource pi, HttpURLConnection httpuc) throws IOException { // If "HTTP//" is found in the beginning, return true. Let / HttpURLConnection parse the mime header itself. / / If this isn't valid HTTP, then we don't try to parse a header / out of the beginning of the response into the responses, / and instead just queue up the output stream to it's very beginning. / This seems most reasonable, and is what the NN browser does. // keepAliveConnections = -1; keepAliveTimeout = 0; boolean ret = false; byte[] b = new byte[8]; try { int nread = 0; serverInput.mark(10); while (nread < 8) { int r = serverInput.read(b, nread, 8 - nread); if (r < 0) { break; } nread += r; } String keep=null; ret = b[0] == 'H' && b[1] == 'T' && b[2] == 'T' && b[3] == 'P' && b[4] == '/' && b[5] == '1' && b[6] == '.'; serverInput.reset(); if (ret) { // is valid HTTP - response started w/ "HTTP/1." responses.parseHeader(serverInput); // we've finished parsing http headers // check if there are any applicable cookies to set (in cache) if (cookieHandler != null) { URI uri = ParseUtil.toURI(url); // NOTE: That cast from Map shouldn't be necessary but // a bug in javac is triggered under certain circumstances // So we do put the cast in as a workaround until // it is resolved. if (uri != null) cookieHandler.put(uri, (Map>)responses.getHeaders()); } // decide if we're keeping alive: / This is a bit tricky. There's a spec, but most current / servers (10/1/96) that support this differ in dialects. / If the server/client misunderstand each other, the / protocol should fall back onto HTTP/1.0, no keep-alive. // if (usingProxy) { // not likely a proxy will return this keep = responses.findValue("Proxy-Connection"); } if (keep == null) { keep = responses.findValue("Connection"); } if (keep != null && keep.toLowerCase().equals("keep-alive")) { // some servers, notably Apache1.1, send something like: / "Keep-Alive: timeout=15, max=1" which we should respect. // HeaderParser p = new HeaderParser( responses.findValue("Keep-Alive")); if (p != null) { // default should be larger in case of proxy // keepAliveConnections = p.findInt("max", usingProxy?50:5); keepAliveTimeout = p.findInt("timeout", usingProxy?60:5); } } else if (b[7] != '0') { // / We're talking 1.1 or later. Keep persistent until / the server says to close. // if (keep != null) { // / The only Connection token we understand is close. / Paranoia: if there is any Connection header then / treat as non-persistent. /*/ keepAliveConnections = 1; } else { keepAliveConnections = 5; } } …… } 对于java.net包的http,ftp等各种协议的底层实现,可以参考rt.jar下面的几个包的代码: sun.net.www.protocl下的几个包。 在http client中也可以设置代理: HostConfiguration conf = new HostConfiguration(); conf.setHost(host); conf.setProxy(ip, 80); statusCode = httpclient.executeMethod(conf,getMethod); httpclient自己也是基于socket封装的http处理的库。底层代理的实现是一样的。 另外一种不设置代理,通过反射修改InetAddress的cache也是ok的。但是这种方法非常不推荐,不要使用,因为对于proxy代理服务器概念了解不清楚,最开始还使用这种方法, public static void jdkDnsNoCache(final String host, final String ip) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (StringUtils.isBlank(host)) { return; } final Class clazz = java.net.InetAddress.class; final Field cacheField = clazz.getDeclaredField("addressCache"); cacheField.setAccessible(true); final Object o = cacheField.get(clazz); Class clazz2 = o.getClass(); final Field cacheMapField = clazz2.getDeclaredField("cache"); cacheMapField.setAccessible(true); final Map cacheMap = (Map) cacheMapField.get(o); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { synchronized (o) {// 同步是必须的,因为o可能会有多个线程同时访问修改。 // cacheMap.clear();//这步比较关键,用于清除原来的缓存 // cacheMap.remove(host); if (!StringUtils.isBlank(ip)) { InetAddress inet = InetAddress.getByAddress(host,IPUtil.int2byte(ip)); InetAddress addressstart = InetAddress.getByName(host); Object cacheEntry = cacheMap.get(host); cacheMap.put(host,newCacheEntry(inet,cacheEntry)); // cacheMap.put(host,newCacheEntry(newInetAddress(host, ip))); }else{ cacheMap.remove(host); } // System.out.println(getStaticProperty( // "java.net.InetAddress", "addressCacheInit")); // System.out.println(invokeStaticMethod("java.net.InetAddress","getCachedAddress",new // Object[]{host})); } } catch (Throwable te) { throw new RuntimeException(te); } return null; } }); final Map cacheMapafter = (Map) cacheMapField.get(o); System.out.println(cacheMapafter); } 关于java中对于DNS的缓存设置可以参考: 1.在${java_home}/jre/lib/secuiry/java.secuiry文件,修改下面为 networkaddress.cache.negative.ttl=0 DNS解析不成功的缓存时间 networkaddress.cache.ttl=0 DNS解析成功的缓存的时间 2.jvm启动时增加下面两个启动环境变量 -Dsun.net.inetaddr.ttl=0 -Dsun.net.inetaddr.negative.ttl=0 如果在java程序中使用,可以这么设置设置: java.security.Security.setProperty("networkaddress.cache.ttl" , "0"); java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0"); 还有几篇文档链接可以查看: http://www.rgagnon.com/javadetails/java-0445.html http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6247501 linux下关于OS DNS设置的几个文件是 /etc/resolve.conf /etc/nscd.conf /etc/nsswitch.conf http://www.linuxfly.org/post/543/ http://linux.die.net/man/5/nscd.conf http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO:Ch18:_Configuring_DNS http://linux.die.net/man/5/nscd.conf

使用Java正则表达式匹配、替换HTML内容

Posted on

使用Java正则表达式匹配、替换HTML内容

51CTO首页 | 新闻 | 专题 | 论坛 | 博客 | 技术圈 | 读书 | 技术频道| CIO| 存储| 地图 | English

首页 | Java | .Net | Web | XML | 语言工具 | 测试 | 游戏 | 移动 | 架构 | 项目管理 | 全部文章 您所在的位置: 首页 > 开发 > JAVA > JAVA专区 > 基础教程 >

使用Java正则表达式匹配、替换HTML内容

http://developer.51cto.com/ 2009-06-10 13:51 新浪科技 我要评论(0)

  • 摘要:本文向您介绍使用Java正则表达式匹配和替换HTML的内容,作者介绍了两种方法,一种用于替换链接地址,一种用于替换图片。
  • 标签:Java正则表达式 匹配 替换 *

曾经了解过JavaScript的正则表达式,知道其功能的强大,对于处理文本比用普通的API处理不管从效率上还是从功能上都有很大的优势。今天项目要求用到Java的正则表达式,于是在网上Google,找到一个Jakarta ORO的库,听说是Java中功能最强大的正则表达式库,确实也如此,Sun公司的JDK里自带的正则表达式功能是远远不如ORO库,从正则表达式的角度上看,其比普通的API处理文本是复杂很多。

但如果应用得恰当的话,会提高工程的质量,于是项目中就应用了这个ORO库,把浏览器请求得到的HTML页面进行解释替换实现一个代理采集信息的功能。感觉自己好像是在开发软件,不是在设计网页。正则表达式有一个很好用的工具--RegexBuddy,应用这个工具可以调度一个匹配你需要的正则表达式串,经过几番调度,把一些HTML标签的正则表达式匹配出来。

第一:像网页链接之间的内容中[URL[绝对地址替换成相对地址,首先要查找匹配这个链接,查找匹配这个串的正则表达式串为

(<\s/a\s+(?:[^\s>]\s/){0,})href\s/=\s/(\"|'|)([^\2\s>]/)\2((?:\s/[^\s>]){0,}\s/>)*

  1. //查找匹配的代码如下:
  2. String patternStrs="(<\s/a\s+(?:[^\s>]\s/){0,})href\s/=\s/ (\"|'|)([^\2\s>]/)\2((?:\s/[^\s>]){0,}\s /*>)";
  3. PatternCompiler complier = new Perl5Compiler();
  4. PatternMatcher matcher = new Perl5Matcher();
  5. Pattern patternForLink = complier.compile(patternStrs,
  6. Perl5Compiler.
  7. CASE_INSENSITIVE_MASK);
  8. PatternMatcherInput input = new PatternMatcherInput(htmlContent);
  9. while (matcher.contains(input, patternForLink)) {
  10. MatchResult match = matcher.getMatch();
  11. //处理匹配的结果,是要替换还是要其他处理
  12. }

第二:对其他的标签也类似只要把匹配的字符串改一下为要匹配的标签就可以了。(如IMG标签)

(<\s/img\s+(?:[^\s>]\s/){0,})src\s/=\s/("|'|)([^\2\s>]/)\2((?:\s/[^\s>]){0,}\s/>),*这样就可以处理

的标签匹配,对其他的标签也一样.

总结:对于大量要处理的文本,建议还是用到正则表达式,而要处理的文本比较少时,用普通的字符串API处理函数就足够了。

【编辑推荐】

  1. Java正则表达式的解释说明
  2. JAVA正则表达式4种常用的功能
  3. Java正则表达式之group()
  4. Java正则表达式入门
  5. Java正则表达式初学者使用法简介 【责任编辑:red7 TEL:(010)68476606】 原文:使用Java正则表达式匹配、替换HTML内容

上一篇: Java正则表达式工具类实例 下一篇: Java GUI的发展和演化简史

ASP.NET数据库开发手册

51CTO教你做SEO狂人 HTML 5 下一代Web开发标准详解

Scala编程语言 大型网站架构技术专家谈 查看所有评论()

验证码: (点击刷新验证码) 匿名发表

频道推荐

更多>>

刀片服务器 云计算 ARP攻防 思科培训

全站热点

更多>>

ARP攻击防范与解决方案

ARP攻击防范与..

2009年上半年软考最新试题与答案

2009年上半年..

技术人

更多>>

乔布斯病假月底..

魔兽易主,三大..

更多>>

优秀博文

更多>>

最新热帖

更多>>

技术快讯

查看样刊

Copyright©2005-2009 51CTO.COM 版权所有

远程会话与远程桌面同步关闭问题

Posted on

远程会话与远程桌面同步关闭问题

远程会话与远程桌面同步关闭问题
来源:中国自学编程网
发布日期:2008-06-03
在日常操作中,网管员往往哪个需要通过远程桌面在主机中进行下载、文件安装、程序运行等等操作,这时,即使管理员推出远程桌面我们也希望这些操作照常进行,不要中断,不过在实际情况中却有很多情况不是这样,只要管理员退出这些操作就会同步中断,给网管员的操作带来了很大的不便。从理论上来说,在对服务器主机进行远程控制时,网络管理员只要不对服务器系统执行系统注销操作或重新启动操作,只是简单地单击远程桌面连接窗口右上角处的关闭按钮时,那些通过远程控制方式启动运行的应用程序还应该继续以后台方式运行,并不会跟随远程桌面连接窗口的关闭而同步关闭。但为什么会出现同步关不的问题呢,经过笔者的观察,这主要是设置的问题,只要我们进行了正确的设置,就完全可以避免此种情况的发生。现在,本文就将该故障的详细排除过程贡献出来:

首先看看在远程登录服务器系统时使用的帐号设置是否正确,如果登录帐号的权限不够或者属性参数设置不当的话,那么就容易出现远程会话同步关闭的现象。假设网络管理员以系统管理员帐号“administrator”来远程登录服务器系统的,在检查“administrator”帐号的设置正确性时,我们可以在服务器系统中用鼠标右键单击桌面上的“我的电脑”图标,从弹出的右键菜单中执行“管理”命令,打开服务器系统的计算机管理界面。在该界面的左侧显示区域,用鼠标依次展开“系统工具”/“本地用户和用户组”/“用户”分支选项,在对应“用户”分支选项的右侧显示区域中,选中目标登录帐号“administrator”,并用鼠标右键单击该帐号,再执行右键菜单中的“属性”命令,打开对应帐号的属性设置界面;单击该设置界面中的“会话”选项卡,在对应的选项设置界面中我们会看到“空闲会话限制”、“活动会话限制”、“结束已断开的会话”、“当达到会话极限或连接中断时如何操作的设置”等几个参数(如图1所示)。其中“空闲会话限制”选项是在服务器系统中没有进行任何操作时所要设置的一项参数,“活动会话限制”选项是用来限制服务器系统中活动连接持续使用时间的一种参数,“结束已断开的会话”选项是用来强行关闭某个会话连接的一项参数。为了避免远程会话同步关闭现象的发生,我们必须在这里将上面的各项参数全部修改为“从不”,以确保远程会话不会被服务器系统强行关闭。

图1

图1

其次检查服务器系统中的终端服务配置参数是否正确,如果终端服务器模式设置不当的话,也可能引起远程会话同步关闭的现象。打开服务器系统的“开始”菜单,从中依次选择“程序”/“管理工具”/“终端服务配置”选项,进入终端服务配置界面,选中该界面左侧显示区域的“服务器设置”选项,并在对应该选项的右侧显示区域我们就能看到终端服务器模式究竟是什么了,要是发现终端服务器模式不是“应用程序服务器”模式时,我们必须及时修改过来,并且还需要在这里将“活动桌面”功能启用起来(如图2所示)。

图2

图2

下面我们还要对远程终端服务属性界面中的一些参数进行检查,并且这里的参数设置优先级一般要高于系统登录帐号属性界面中的参数设置。在进行这种检查时,我们可以先按照前面的操作打开服务器系统的终端服务配置界面,之后依次选中“终端服务配置”/“连接”选项,在对应该选项右侧显示区域中用鼠标右键单击“RDP-TCP”选项,从弹出的快捷菜单中执行“属性”命令,打开远程终端服务属性设置界面(如图3所示);在该设置界面中我们看到了“替代用户设置”这个选项参数,要是将该选项参数选中的话,那么我们之前在系统登录帐号属性界面中设置的各项参数都将不能发挥作用,所有参数都会自动按照远程终端服务属性设置界面中的参数进行处理,要是没有选中“替代用户设置”这个选项参数时,那么我们之前在系统登录帐号属性界面中设置的各项参数才能生效。而且,“替代用户设置”设置项下面,我们同样也会看到“空闲会话限制”、“活动会话限制”、“结束已断开的会话”、“当达到会话极限或连接中断时如何操作的设置”等几个参数,我们可以根据工作需要进行有针对性设置就行了。

图3

图3

网络管理员在远程控制单位服务器系统时,发现这里的“替代用户设置”选项被意外选中了,同时“结束已断开的会话”参数也被设置为了1分钟,这也是为什么网络管理员通过远程桌面连接在服务器系统中启动某个会话连接后,单击远程桌面连接窗口中的关闭按钮时该会话连接也会同步关闭的原因。找到故障原因后,问题就很好解决了,网络管理员在这里将“结束已断开的会话”参数设置为了“从不”后,就立即解决了服务器远程会话同步关闭故障。  ![]() 相关文章  关于 **远程会话与远程桌面同步关闭问题** ·[ADSl浅析](http://www.zxbc.cn/html/20080530/51611.html)

·Windows 2000 Server DNS维护一点通 ·用"连接共享"实现ADSL共享上网 ·通过NETBIOS实现信息收集与渗透(1) ·未公开的Windows网络工具 ·去除Windows 2000的默认共享 新闻动态 ·网络电视突遇监管风暴 腾讯QQlive停播部份节目 ·熊猫烧香病毒案告破 8犯罪嫌疑人被抓获 ·第三届中国(南京)国际软件产品博览会 ·百度将推新一代营销平台“我的营销中心” ·微软收购企业群组通讯软件商Parlano ·Sun和微软加深合作成立了Sun/微软协作中心 ·大企业领袖“高薪低能排行榜” ·入侵省内多所高校计算机系统,制贩假文凭被捕 ·戴尔代工厂被曝出违反《劳动法》有关规定 ·互联网公司应主动"锻炼"积极"过冬" 栏目推荐 ·让PXE无盘工作站使用固定的IP地址 ·网络数据库的复制和同步(2) ·需要密码的Windows XP系统的共享文件夹 ·巧设IP地址便于简化管理网络 ·利用Win XP自带工具实现远程管理 ·在网络服务中避免远程引用 专家博客 程序人生 编程的首要原则是? 编程的首要原则是? 北漂IT人如何崛起网络间 北漂IT人如何崛起网络 ·JBoss创始人Marc Fleury的成功职业生涯 ·怎样才能成为高手? ·亲历惊心48小时,抢救35亿交易数据 ·微软架构师谈编程语言发展(一) ·IT人你除了IT还能干什么? ·电子工程师也是十余年了 关于站点 - 联系我们 - 版权隐私 - - 返回顶部 中国自学编程网版权所有 本站原创文章,未经授权禁止转载或建立镜象站点 E-Mail:520it@163.com Tel:15802529892 Copyright 2006-2008 Zxbc.cn Corporation 中国自学编程网倡导软件开发学习文化,崇尚软件开源和共享,致力于帮助编程学习者在各自专业领域取得成功!