快速入门 - 几行代码搞定websocket实时通讯
欢迎使用GoEasy!
本文向您展示如何很快的在您的项目中集成websocket消息的发送和接收。
通过本文您将会掌握:
- 集成GoEasy SDK到客户端
- 客户端与GoEasy建立websocket连接
- 客户端订阅一个channel来接收消息
- 通过GoEasy提供的各种语言的服务端代码或Rest接口向前端发送消息
- 一个前端向另一个前端发送消息
在试用的过程中,有任何问题,也可以通过在线咨询获得GoEasy技术人员的帮助。
名词解释
名词 | 解释 |
---|---|
客户端 | 也就是俗称的前端,GoEasy SDK支持绝大多数Web技术开发的前端项目:Html、Vue, React,Taro、Cocos Creator和Unipp,以及各种小程序 |
发送端 | 发送端可以是一个客户端、可以是常见的Python、Java、PHP、Go、Node等技术开发的服务端项目,也可以是其他可以发送Rest请求的应用或设备 |
appkey | 为了方便试用,建议发送端和接收端都先使用Common key |
channel | 根据您的业务,channel可以是您直播间的id, 也可以是一个用户的id, channel可以为任意字符串(不能包含空格和中文),只要接收端和发送端保持一致,就可以收到消息。一个客户端可以订阅多个channel,channel无需创建,可随用随弃。 |
1. 免费注册开发者账号
2. 客户端接收Websocket消息
- Html
- Vue和Uniapp
- 小程序
<script type="text/javascript" src="https://cdn.goeasy.io/goeasy-2.5.11.min.js"></script>
<script type="text/javascript">
//初始化GoEasy对象
let goEasy = GoEasy.getInstance({
host:'hangzhou.goeasy.io', //新加坡host:singapore.goeasy.io
appkey: "您的appkey", //替换为您的应用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: "test_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)
}
});
</script>
import GoEasy from 'goeasy';
// 建议在main.js里初始化全局的GoEasy对象
Vue.prototype.goEasy = GoEasy.getInstance({
host:'hangzhou.goeasy.io', //新加坡host:singapore.goeasy.io
appkey: "您的appkey", //替换为您的应用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: "test_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)
}
});
import GoEasy from './lib/goeasy-2.5.11.min';
//建议在app.js中初始化全局GoEasy对象
App({
onLaunch: function () {
wx.goEasy = GoEasy.getInstance({
host:'hangzhou.goeasy.io', //新加坡host:singapore.goeasy.io
appkey: '您的appkey',//替换为您的应用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: "test_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)
}
});
3. 服务端/客户端发送Websocket消息
发送时channel一定要和接收端channel保持一致,才能收到消息。
- Javascript
- Rest API
- Python
- Java
- PHP
- Node
- Ruby
- C#
//发送
goEasy.pubsub.publish({
channel: "test_channel",//替换为您自己的channel
message: {text:'Hello, GoEasy!'},//替换为您想要发送的消息内容
onSuccess:function(){
console.log("消息发布成功。");
},
onFailed: function (error) {
console.log("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
}
//macOS/Linux 新加坡host:rest-singapore.goeasy.io
curl -X POST https://rest-hangzhou.goeasy.io/v2/pubsub/publish
-H "Content-Type: application/json"
-d "{
'appkey':'您的appkey',
'channel':'test_channel',
'content':'{text:"Hello, GoEasy!"}'
}"
//Windows 新加坡rest-host:rest-singapore.goeasy.io
curl -X POST https://rest-testhangzhou.goeasy.io/v2/pubsub/publish ^
-H "Content-Type: application/json" ^
-d "{ appkey:'您的appkey', channel:'test', content:'{text:"Hello, GoEasy!"} }"
appkey = "BC-xxxxxxxxx"
channel = "test_channel"
content = "{text:'Hello, GoEasy!'}"
data = {"appkey": appkey, "channel": channel, "content": content}
url = "https://rest-hangzhou.goeasy.io/v2/pubsub/publish" // 新加坡rest-host:rest-singapore.goeasy.io
response = requests.post(url, data=data)
添加maven依赖,或手动下载Java SDK
<dependencies>
...
<dependency>
<groupId>io.goeasy</groupId>
<artifactId>goeasy-sdk</artifactId>
<version>0.3.19</version>
</dependency>
</dependencies>
//新加坡rest-host:rest-singapore.goeasy.io
GoEasy goEasy = new GoEasy( "https://rest-hangzhou.goeasy.io”, "BC-xxxxxxxxx");
goEasy.publish("test_channel", "{text:'Hello, GoEasy!'}",new PublishListener(){
@Override
public void onSuccess() {
System.out.println("Publish success.");
}
@Override
public void onFailed(GoEasyError error) {
System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
}
});
//新加坡rest-host:rest-singapore.goeasy.io
$url = 'https://rest-hangzhou.goeasy.io/v2/pubsub/publish';
$post_data = array("appkey"=>"BC-xxxxxxxxx","channel"=>"test_channel","content"=>"{text:'Hello, GoEasy!'}");
echo publish($url,$post_data);
function publish($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
var http = require('http');
var appkey = 'Your appkey';
var channel = 'test_channel';
var content = "{text:'Hello, GoEasy!'}";
var queryParams = 'appkey=' + appkey + '&channel=' + channel + '&content=' + content;
var options = {
hostname: 'rest-hangzhou.goeasy.io', //新加坡rest-host:rest-singapore.goeasy.io
path: '/v2/pubsub/publish',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var req = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (result) => {
console.log('响应结果:',result);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(queryParams);
req.end();
require 'net/http'
class GoEasyClient
def self.send(channel, content)
Thread.new {
Net::HTTP.post_form(URI("https://rest-hangzhou.goeasy.io/v2/pubsub/publish"), //新加坡rest-host:rest-singapore.goeasy.io
{appkey: "BC-xxxxxxxxx", channel: channel, content: content})
}
end
end
string postDataStr = "appkey=BC-xxxxxxxxx&channel=test_channel&content={text:'Hello, GoEasy!'}";
//新加坡rest-host:rest-singapore.goeasy.io
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://rest-hangzhou.goeasy.io/v2/pubsub/publish");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
Stream myRequestStream = request.GetRequestStream();
byte[] data = Encoding.UTF8.GetBytes(postDataStr);
myRequestStream.Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
附录和技术答疑
相信您已经成功的完成GoEasy消息的发送和接收,祝贺您!
更多详情,可以参考文档相关章节:
也可以在线咨询GoEasy技术支持。