一. 本文向您展示如何很快的在您的项目中集成websocket消息的发送和接收。
通过本文您将会掌握:
- 集成GoEasy SDK到客户端
- 客户端与GoEasy建立websocket连接
- 客户端订阅一个channel来接收消息
- 通过GoEasy提供的各种语言的服务端代码或Rest接口向前端发送消息
- 一个前端向另一个前端发送消息
二. 名词解释:
名词 | 解释 |
---|---|
客户端 | 客户端支持Android、 iOS、 Web客户端(Web页面、 Uniapp、 各种小程序、 Cocos Creator) |
发送端 | 发送端可以是一个客户端、可以是常见的Python、Java、PHP、Go、Node等技术开发的服务端项目,也可以是其他可以发送Rest请求的应用或设备 |
appkey | 为了方便试用,建议发送端和接收端都先使用Common key |
channel | 根据您的业务,channel可以是您直播间的id, 也可以是一个用户的id, channel可以为任意字符串(不能包含空格和中文),只要接收端和发送端保持一致,就可以收到消息。一个客户端可以订阅多个channel,channel无需创建,可随用随弃。 |
三. 入门实例:
1. 免费注册开发者账号:
2. 客户端接收Websocket消息:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GoEasy receive</title>
<script type="text/javascript" src="https://cdn.goeasy.io/goeasy-2.8.8.min.js"></script>
<script type="text/javascript">
//初始化GoEasy对象
let goEasy = GoEasy.getInstance({
host: 'hangzhou.goeasy.io', //新加坡host:singapore.goeasy.io
appkey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx", //替换为您的应用appkey
modules: ['pubsub']
});
//建立连接
goEasy.connect({
onSuccess: function () { //连接成功
console.log("GoEasy connect successfully.") //连接成功
},
onFailed: function (error) { //连接失败
console.log("Failed to connect GoEasy, code:" + error.code + ",error:" + error.content);
}
});
//订阅消息
goEasy.pubsub.subscribe({
channel: "客户端",//替换为您自己的channel
onMessage: function (message) { //收到消息
console.log("Channel:" + message.channel + " content:" + message.content);
},
onSuccess: function () {
console.log("Channel订阅成功。");
},
onFailed: function (error) {
console.log("Channel订阅失败, 错误编码:" + error.code + " 错误信息:" + error.content)
}
});
//发送消息
goEasy.pubsub.publish({
channel: "客户端",//替换为您自己的channel
message: "Hello GoEasy333!",//替换为您想要发送的消息内容
onSuccess: function () {
console.log("消息发布成功。");
},
onFailed: function (error) {
console.log("消息发送失败,错误编码:" + error.code + " 错误信息:" + error.content);
}
});
</script>
</head>
<body>
<div id="tip">请打开浏览器控制台,查看输出内容</div>
</body>
</html>
3. 服务端/客户端发送Websocket消息:
发送时channel一定要和接收端channel保持一致,才能收到消息。
3.1 添加maven依赖,或手动下载Java SDK
<repositories> <repository> <id>goeasy</id> <name>goeasy</name> <url> http://maven.goeasy.io/content/repositories/releases/ </url> </repository> </repositories> <dependencies> ... <dependency> <groupId>io.goeasy</groupId> <artifactId>goeasy-sdk</artifactId> <version>0.4.2</version> </dependency> </dependencies>
3.2
package com.deyuan.websocket.test;
import io.goeasy.GoEasy;
import org.junit.jupiter.api.Test;
public class WebSocketTest {
//代码测试
@Test
public void Test() {
// 参数:服务器地址 , AppKey:commonKey
GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
//参数:管道标识,发送内容
goEasy.publish("客户端", "Hello, GoEasy!");
}
}
注意事项:
1. 服务器地址需要根据你在GoEasy控制台创建的应用区域来填写,目前GoEasy主要有两块区域,杭州: rest-hangzhou.goeasy.io,新加坡: rest-singapore.goeasy.io。
2. GoEasy的appkey需要你到GoEasy控制台去获取,java后端发送消息,需要使用common key。
3. html页面作为接收端,其subscribe函数中的channel必须与java后端发送的channel一致,可以完成消息的接收;