powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Servlet -> Applet communication
3 сообщений из 3, страница 1 из 1
Servlet -> Applet communication
    #37839537
kadet
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
всем привет.

имеется web приложение на томкате. Имеется апплет, который отражает некоторые данные. Запросы апплета к сервлету работают как положено. Надо чтобы при определенных обстоятельствах сервлет сообщал апплету о происшедшем событии. Т.е. сервлет является инициатором сообщения.

коллеги, подскажите плз. (поделитесь опытом), существует ли реализация такой модели поведения ?

Теоретически можно пустить в апплете поток, который бы пинговал сервлет и в случае события "вытягивал" данные от сервлета. Но эта модель не красивая.

спасибо
...
Рейтинг: 0 / 0
Servlet -> Applet communication
    #37839575
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Servlet -> Applet communication
    #37840402
kadet
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Blazkowicz http://www.sql.ru/forum/actualthread.aspx?tid=947836
большое спасибо. работает.

я немного изменил код, чтобы можно было общаться на уровне объектов:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
public class StateNotifier extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ServerMessage<String> serverMessage =null;
	private ByteArrayOutputStream baos = null;
	private ObjectOutputStream oos = null;
	
	@Override
	public void init() throws ServletException {
		super.init();
		try {
			baos=new ByteArrayOutputStream();
			oos=new ObjectOutputStream(baos);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void service(ServletRequest arg0, ServletResponse response) throws ServletException, IOException {
		ServletOutputStream out = response.getOutputStream();

//		String head = "HTTP/1.0 200 OK\n" + "Server: VoltmeterServlet\n"
//				+ "Content-Type: text/html; charset=utf-8\n"
//				+ "Connection: Keep-Alive\n"
//				+ "Content-Encoding: multipart/mixed\n"
//				+ "Transfer-Encoding: chunked" + "Pragma: no-cache\n\n";
//		
//		oos.writeObject(head);
//		out.write(baos.toByteArray());
//		
//		baos.reset();
		
		try {
			while (true) {
				serverMessage = new ServerMessage<String>("my serverMessage ["+(System.currentTimeMillis()/1000)+"]");
				System.out.println(serverMessage.getEntity());
				
				oos.writeObject(serverMessage);
				out.write(baos.toByteArray());
				out.flush();
				baos.reset();
				
				Thread.currentThread().sleep(3000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}



обращаю внимание, что в случае с апплетом информация для заголовка проигнорированна.

а вот вызов из апплета:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
	private class ServerStateNotifierRunnable implements Runnable{
		
		@Override
		public void run() {
			
			HttpURLConnection connection = null;
			try {
				String urlParameters = "smth=9";
				
				URL url = new URL(homeUrl+"/StateNotifier");
				connection=(HttpURLConnection) url.openConnection();
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
				connection.setRequestProperty("Content-Length", "" +  Integer.toString(urlParameters.getBytes().length));
				connection.setRequestProperty("Content-Language", charset);  
				
				connection.setUseCaches (false);
				connection.setDoInput(true);
				connection.setDoOutput(true);
				
				//Send request
				DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
				wr.writeBytes (urlParameters);
				wr.flush ();
				wr.close ();
				
				//Get Response
				ObjectInputStream ois= new ObjectInputStream(connection.getInputStream());
				Object response;

				try {
					while(true){
						
						response = ois.readObject();
						
						if(response instanceof ServerMessage){
							if(((ServerMessage<?>)response).getMessageType().equals(ServerMessageType.ERROR)){
								ServerMessage<Exception> errMessage=(ServerMessage<Exception>) response;
								JOptionPane.showMessageDialog(PRMModellerGUI.this.parent, errMessage.getEntity().getMessage(), resourceBundle.getString("layout.policy.changed.error.title"), JOptionPane.ERROR_MESSAGE);
								return ;
							}
							ServerMessage<String> theServerMessage = (ServerMessage<String>)response;
							System.out.println(theServerMessage.getEntity());
							
						}else{
//							JOptionPane.showMessageDialog(parent, "Unknown responce [load processing list]", resourceBundle.getString("layout.policy.changed.error.title"), JOptionPane.ERROR_MESSAGE);
//							return ;
							System.out.println("somthing wrong");
						}
						
						try {
							if(ois.available() >0 ){
								continue;
							}else{
								Thread.currentThread().sleep(100);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						
					}
				} catch (ClassNotFoundException cnfe) {
					logger.log(Level.WARNING, cnfe.getLocalizedMessage(), cnfe);
				}
				
			} catch (IOException ioe) {
				logger.log(Level.WARNING, ioe.getLocalizedMessage(), ioe);
			}finally{
				if(connection != null){
					connection.disconnect();
				}
				
			}
			
			
		}
		
	}



кстати говоря я не заметил каких-бы то ни было ограничений связанных с высказыванием коллеги:

rrrrrrrrЭто и есть комет :)

Надо только помнить, что всё отправленное висит на клиенте в памяти, пока респонс не завершится. Поэтому рекомендуется периодически переоткрывать запрос (посылать новый).

вероятно это связанно с тем, что GC в апплете работает тоже.
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Servlet -> Applet communication
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]