当前位置: 首页 > 工具软件 > Auto Comet > 使用案例 >

comet java_java 实现长链接Comet

金令秋
2023-12-01

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();

}

}

 类似资料: