天天看点

WebSocket基础入门-前端发送消息

项目结构如下图:

WebSocket基础入门-前端发送消息

TestSocket.java

package com.charles.socket;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/helloSocket")
public class TestSocket {

    /***
     * 当建立链接时,调用的方法.
     * @param session
     */
    @OnOpen
    public void open(Session session) {
        
        System.out.println("开始建立了链接...");
        System.out.println("当前session的id是:" + session.getId());
    }
    
    /***
     * 处理消息的方法.
     * @param session
     */
    @OnMessage
    public void message(Session session, String data) {
        
        System.out.println("开始处理消息...");
        System.out.println("当前session的id是:" + session.getId());
        System.out.println("从前端页面传过来的数据是:" + data);
    }
}
           

index.jsp 代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Charles-WebSocket</title>

<script type="text/javascript">
    
    var websocket = null;
    var target = "ws://localhost:8080/websocket/helloSocket";
    
    function buildConnection() {
        
        if('WebSocket' in window) {
            websocket = new WebSocket(target);        
        } else if('MozWebSocket' in window) {
            websocket = MozWebSocket(target);
        } else {
            window.alert("浏览器不支持WebSocket");
        }
    }
    
    // 往后台服务器发送消息.
    function sendMessage() {
        
        var sendmsg = document.getElementById("sendMsg").value;
        console.log("发送的消息:" + sendmsg);
        
        // 发送至后台服务器中.
        websocket.send(sendmsg);
    }
    
</script>
</head>
<body>
    
    <button onclick="buildConnection();">开始建立链接</button>
    <hr>
    <input id="sendMsg" /> <button onclick="sendMessage();">消息发送</button>

</body>
</html>
           

注意:

  和后台交互的时候,一定要先点击:开始建立连接。你懂的...没有建立连接的话,是不能发送消息的。

WebSocket基础入门-前端发送消息

先点击,开始建立连接,然后在文本框中输入内容:我是Charles,点击消息发送,在看后台日志。

WebSocket基础入门-前端发送消息
WebSocket基础入门-前端发送消息

转载于:https://my.oschina.net/u/4193800/blog/3097864