comet java_java 实现长链接Comet

importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLEncoder;importjava.util.ArrayList;importjava.util.List;importjava.util.Random;importjava.util.ResourceBundle;importnet.sf.json.JSONObject;public classHttpCometUtils {//private static String host = "http://localhost:8080/Comet/";

private static String action = "json/home!SendMsg.do?msgType=ALL";protected static ResourceBundle projectBundle =ResourceBundle

.getBundle("DataBaseServer");public static Thread CometThread = null;private static String host = projectBundle.getString("web_server");public static boolean isLogin = false;static{if (!host.endsWith("/")) {

host+= "/";

}

}publicHttpCometUtils() {//host = "http://localhost:8080/Comet/";

if (!host.endsWith("/")) {

host+= "/";

}

}/***@paramurlString

*@parammethod

*@paramtype

*@parammsg

*@throwsIOException*/

public static voidconnectServer() {newThread() {

@Overridepublic voidrun() {int errorCount = 0;while(isLogin) {if (errorCount >= 10) {try{

Thread.sleep(15000);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();break;

}

}

URL url= null;

HttpURLConnection urlConnection= null;try{

String serverURL=host+ "CometServlet?content=&type=wait&msgType=lott";

System.out.println(serverURL);

url= newURL(serverURL);

urlConnection=(HttpURLConnection) url

.openConnection();

urlConnection.setRequestMethod("GET");

urlConnection.setDoOutput(true);

urlConnection.setDoInput(true);

urlConnection.setUseCaches(false);

InputStream is=urlConnection.getInputStream();byte[] b = new byte[is.available()];

is.read(b);

String jsmsg= new String(b, "utf-8");

System.out.println(jsmsg);if(jsmsg.equals("")){

jsmsg= "{}";

}

JSONObject json=JSONObject.fromObject(jsmsg);

Object obj= null;if (json.containsKey("type")) {

obj= json.get("type");if (obj != null && "lott".equals(obj)) {

json= (JSONObject) json.get("msg");if (json.containsKey("chatMsg")) {

System.out.println(json.get("chatMsg"));

}

}

}

errorCount= 0;

}catch(MalformedURLException e) {

errorCount++;//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {

errorCount++;//TODO Auto-generated catch block

e.printStackTrace();

}catch(Exception e) {

errorCount++;

e.printStackTrace();

}finally{if (urlConnection != null) {

urlConnection.disconnect();

}

}

}

}

}.start();

}public static voidmain(String[] args) {int x = new Random(System.currentTimeMillis()).nextInt(100);

HttpCometUtils.isLogin= true;

HttpCometUtils.connectServer();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值