El Noguer

Joaquim Perez i Noguer


Filed under: Ciència i tecnologia — Joaquim Perez Noguer at 5:24 pm on Dijous, Agost 1, 2019

Exemple de crear un servidor Websocket en Java7 i el client amb Javascript


import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
public class HelloWorldEndpoint {
    public String hello(String message) {
        System.out.println("Received : "+ message);
        return "Hello form the Server!";
    public void myOnOpen(Session session) {
        System.out.println("WebSocket opened: " + session.getId());
    public void myOnClose(CloseReason reason) {
        System.out.println("Closing a due to " + reason.getReasonPhrase());
    public void error(Throwable t) {      
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <meta charset="utf-8">
        <title>Your First WebSocket!</title>
        <script language="javascript" type="text/javascript">
            var wsUri = "ws://localhost:8080/javaee7-websocket-basic/hello";
            function init() {
                output = document.getElementById("output");
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                websocket.onmessage = function(evt) {
                websocket.onerror = function(evt) {
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            function onError(evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                // You can close communication at any time
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
            window.addEventListener("load", init, false);
        <h1 style="text-align: center;">Hello World WebSocket Client</h2>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send Message" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
        <div id="output"></div>

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>