Pour WebSocket Server créé par Java Plusieurs clients Java WebSocket et JavaScript WebSocket se connectent et Supposons que les messages des clients sont diffusés à chaque client.
Server : Java
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/hellowebsocket")
public class ChatWebSocket {
//Tous les clients
private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
//Le client qui a envoyé le message
private Session currentSession = null;
/*
*Lorsque la connexion s'ouvre
*/
@OnOpen
public void onOpen(Session session, EndpointConfig ec) {
sessions.add(session);
currentSession = session;
}
@OnMessage
public String onMessage(String message) throws IOException {
Iterator<Session> it = sessions.iterator();
while (it.hasNext()) {
Session s = it.next();
if (s != currentSession) {
s.getBasicRemote().sendText(message);
}
}
return message;
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
}
}
Client 1 : Java
import java.net.URI;
import java.util.Scanner;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
public class Client {
public static void main(String[] args) throws Exception {
String msg;
Scanner scanIn = new Scanner(System.in);
//Obtenez l'objet conteneur WebSocket pour l'initialisation
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
//URI du point de terminaison du serveur
URI uri = URI.create("ws://localhost:8080/hellowebsocket");
//Établir une session avec le point de terminaison du serveur
Session session = container.connectToServer(new WebSocketClientMain(), uri);
while (true) {
msg = scanIn.nextLine();
session.getBasicRemote().sendText(msg);
if (msg.equals("")) {
break;
}
}
scanIn.close();
session.close();
}
}
Client 1 : maven
<dependencies>
<!-- https://mvnrepository.com/artifact/org.glassfish.tyrus.bundles/tyrus-standalone-client -->
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.16</version>
</dependency>
</dependencies>
Client 2 : JavaScript
<html>
<head>
<title>Chat</title>
<script type="text/javascript" src="./jquery.js"></script>
<script>
var fullpath = document.location.pathname;
var path = fullpath.substring(0, fullpath.lastIndexOf("/"));
var url = "ws://" + document.location.host + path + "/hellowebsocket";
var ws = new WebSocket(url); //important
$(function() {
$("#button-search").click(postChat);
ws.onmessage = function(receive) {
$("#message").text(receive.data);
};
});
function postChat() {
var text = $("#q").val();
var state = ws.readyState;
if (state == ws.OPEN) {
ws.send(text);
} else {
alert("connection state is not OPEN: " + state);
}
}
</script>
</head>
<body>
<div>
<div id="inputform">
<textarea id="q" cols="80" rows="2"></textarea>
<input type="button" id="button-search" value="POST" />
</div>
</div>
<div id="message"></div>
</body>
</html>
Recommended Posts