`
muscle-liu
  • 浏览: 227761 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

HttpURLConnection 与 servlet 实现同一应用在不同主机上的通信

阅读更多
最近的web项目(J2ee + Flex)求在多台主机上运行,用的是同一个数据库,实现简单的集群。具体的集群还没实现,但我的啊head要求我实现一个IM(InstantMessage即时信息)功能。这功能不难,难就在于各用户是登录在不用的主机上,要解决不同主机间的通信。

同一应用在不同主机间的通信,我想可以有两种方法:1)用java socket; 2)用http request(其实,http request的底层也是socket连接的,是对socket高层次的封装。)。

考虑到实现上的方便,我就选用了http request来实现通信(原理如下):

       先用 java HttpURLConnection 来发送http请求(因为一般的jsp/servlet发送请求时是会转向一个web地址的,这对于IM功能来说是没需要的)。根据各主机的地址,创建不同的 HttpURLConnection 。然后用一个 servlet 来处理请求,并处理相应的 IM 信息。

HttpURLConnection 实现的主要代码:

String[] reqPath;//各主机的请求路径

// 记录各主机的 URL 和相应的 HttpURLConnection
URL[] url;
HttpURLConnection[] httpURLConnection;
......
......

public void sendMessage( String sender, String msg, String receiver) {

	try {
		msg = URLEncoder.encode(msg, "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	url = new URL[reqPath.length];
	httpURLConnection = new HttpURLConnection[reqPath.length];
	for (int i = 0; i < reqPath.length; i++) {
		String urlPath = reqPath[i] + "?sender="+sender+"&msg=" + msg + "&receiver="
				+ receiver;
		System.out.println("urlPath: " + urlPath);
		try {
			url[i] = new URL(urlPath);

			httpURLConnection[i] = (HttpURLConnection) url[i]
					.openConnection();

			System.out.println("url[" + i + "]: " + url[i]);
			System.out.println("httpURLConnection[" + i + "]: "
					+ httpURLConnection[i]);

			httpURLConnection[i].setConnectTimeout(5000);
			httpURLConnection[i].setRequestMethod("POST");
			httpURLConnection[i].setDoOutput(true);
			httpURLConnection[i].setRequestProperty("Content-Type",
					"text/html;charset=UTF-8");
			httpURLConnection[i].setRequestProperty("Cache-Control",
					"no-cache");
			httpURLConnection[i].connect();

			InputStream is = httpURLConnection[i].getInputStream();
			int resCode = httpURLConnection[i].getResponseCode();
			System.out.println("ResponseCode:" + resCode);					
			is.close();
			
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
	}
	if (httpURLConnection != null) {
		for (int i = 0; i < httpURLConnection.length; i++) {
			httpURLConnection[i].disconnect();
		}
		httpURLConnection = null;
	}
	if (url != null) {
		url = null;
	}
}

.........


在测试中,因为所发送的 message 的是有空格,所以构造出来的 URL 也是有空格的。这对IE来说是不允许的(测试中出现了 "Server returned HTTP response code: 505"  的 exception )。所以上边代码中有 "msg = URLEncoder.encode(msg, "UTF-8");" 这一句来处理。而在处理请求的 servlet 中我们可以用 "content = URLDecoder.decode(content,"UTF-8");" 来还原 message。

小结:想实现web简单的集群,HttpURLConnection 与 servlet 就可以解决,并不需要其他高深的技术或框架。
5
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics