快速入门 - 几行代码搞定websocket实时通讯
欢迎使用GoEasy!
本文向您展示如何很快的在您的项目中集成websocket消息的发送和接收。
通过本文您将会掌握:
- 集成GoEasy SDK到客户端
- 客户端与GoEasy建立websocket连接
- 客户端订阅一个channel来接收消息
- 通过GoEasy提供的各种语言的服务端代码或Rest接口向前端发送消息
- 一个前端向另一个前端发送消息
在试用的过程中,有任何问题,也可以通过在线咨询获得GoEasy技术人员的帮助。
名词解释
名词 | 解释 |
---|---|
客户端 | 客户端支持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消息
- Html
- Vue和Uniapp
- 小程序
- Android
- iOS
<script type="text/javascript" src="https://cdn.goeasy.io/goeasy-2.6.6.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.6.6.min';
//建议在app.js中初始化全局GoEasy对象
App({
onLaunch: function () {
wx.goEasy = GoEasy.getInstance({
host:'hangzhou.goeasy.io', //新加坡host:singapore.goeasy.io
appkey: '您的appkey',//替换为您的应用appkey
modules: ['pubsub']
});
}
})
//建立连接
wx.goEasy.connect({
onSuccess: function () { //连接成功
console.log("GoEasy connect successfully.") //连接成功
},
onFailed: function (error) { //连接失败
console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
}
});
//订阅消息
wx.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)
}
});
添加SDK依赖
dependencies {
implementation 'io.goeasy:goeasy-client-java:0.1.4'
}
初始化、建立连接和接收(订阅)消息
//初始化GoEasy,新加坡host:singapore.goeasy.io
GoEasy.init(“hangzhou.goeasy.io”, "您的appkey", this.getApplicationContext());
//连接GoEasy
GoEasy.connect(new ConnectEventListener() {
@Override
public void onSuccess(GResult data) {
Log.i("GoEasy","连接成功");
}
@Override
public void onFailed(GResult error) {
Log.i("GoEasy","Failed to connect GoEasy, code:" + error.getCode() + ",error:" + error.getData());
}
@Override
public void onProgress(int attempts) {
Log.i("GoEasy", "GoEasy connect progress attempts: " + attempts);
}
});
//接收(订阅消息)
GPubSub.subscribe("test_channel", new SubscribeEventListener() {
@Override
public void onMessage(PubSubMessage message) {
Log.i("GoEasy",message.getContent());
}
@Override
public void onSuccess(GResult data) {
Log.i("GoEasy","订阅成功");
}
@Override
public void onFailed(GResult error) {
Log.i("GoEasy","订阅失败,错误编码:" + error.getCode() + " 错误信息:" + error.getData());
}
});
快速推进中,敬请期待
3. 服务端/客户端发送Websocket消息
发送时channel一定要和接收端channel保持一致,才能收到消息。
- Javascript
- Android
- iOS
- Rest API
- Python
- Java
- PHP
- Go
- Node
- C#
- Ruby
//发送
goEasy.pubsub.publish({
channel: "test_channel",//替换为您自己的channel
message: "Hello, GoEasy!",//替换为您想要发送的消息内容
onSuccess:function(){
console.log("消息发布成功。");
},
onFailed: function (error) {
console.log("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
}
//发送消息
GPubSub.publish("test_channel", content, new GoEasyEventListener() {
@Override
public void onSuccess(GResult gResult) {
Log.i("GoEasy", gResult.getData().toString());
}
@Override
public void onFailed(GResult error) {
Log.i("GoEasy","消息发送失败,错误编码:" + error.getCode() + " 错误信息:" + error.getData());
}
});
快速推进中,敬请期待
//macOS/Linux 新加坡host:rest-singapore.goeasy.io
curl -X POST https://rest-hz.goeasy.io/v2/pubsub/publish \
-H "Content-Type: application/json" \
-d "{
'appkey':'您的appkey',
'channel':'test_channel',
'content':'Hello, GoEasy!'
}"
//Windows 新加坡rest-host:rest-singapore.goeasy.io
curl -X POST https://rest-hz.goeasy.io/v2/pubsub/publish ^
-H "Content-Type: application/json" ^
-d "{ appkey:'您的appkey', channel:'test_channel', content:'Hello, GoEasy!' }"
import requests
from requests.structures import CaseInsensitiveDict
# 新加坡rest-host:rest-singapore.goeasy.io
url = "https://rest-hz.goeasy.io/v2/pubsub/publish"
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
data = """
{
"appkey": "您的appkey",
"channel": "test_channel",
"content": "Hello, GoEasy!"
}
"""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
添加maven依赖,或手动下载Java SDK
<dependencies>
...
<dependency>
<groupId>io.goeasy</groupId>
<artifactId>goeasy-sdk</artifactId>
<version>0.4.2</version>
</dependency>
</dependencies>
//新加坡rest-host:rest-singapore.goeasy.io
GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "您的appkey");
goEasy.publish("test_channel", "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());
}
});
<?php
// 新加坡rest-host:rest-singapore.goeasy.io
$url = "https://rest-hz.goeasy.io/v2/pubsub/publish";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = <<<DATA
{
"appkey": "您的appkey",
"channel": "test_channel",
"content": "Hello, GoEasy!"
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func publishMessage(channel string, content string) {
url := "https://rest-hz.goeasy.io/v2/pubsub/publish"
data := map[string]string{
"appkey": "您的appkey",
"channel": channel,
"content": content,
}
jsonValue, _ := json.Marshal(data)
response, err := http.Post(url, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
fmt.Printf("The HTTP request failed with error %s", err)
} else {
fmt.Println(response.Status)
}
}
func main() {
publishMessage("test_channel", "Hello, GoEasy!")
}
const http = require("https");
const options = {
hostname: "rest-hz.goeasy.io", //新加坡rest-host:rest-singapore.goeasy.io
path: "/v2/pubsub/publish",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
appkey: "您的appkey",
channel: "test_channel",
content: "Hello, GoEasy!"
};
let result = "";
const req = http.request(options, (res) => {
console.log(res.statusCode);
res.setEncoding("utf8");
res.on("data", (chunk) => {
result += chunk;
});
res.on("end", () => {
console.log(result);
});
});
req.on("error", (e) => {
console.error(e);
});
req.write(JSON.stringify(data));
req.end();
// 新加坡rest-host:rest-singapore.goeasy.io
var url = "https://rest-hz.goeasy.io/v2/pubsub/publish";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/json";
var data = @"{
""appkey"": ""您的appkey"",
""channel"": ""test_channel"",
""content"": ""Hello, GoEasy!""
}";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Console.WriteLine(httpResponse.StatusCode);
require 'net/http'
# 新加坡rest-host:rest-singapore.goeasy.io
url = "https://rest-hz.goeasy.io/v2/pubsub/publish"
appkey = "您的appkey"
channel = "test_channel"
content = "Hello, GoEasy!"
response = Net::HTTP.post_form(URI(url), {appkey: appkey, channel: channel, content: content})
puts response.code
附录和技术答疑
相信您已经成功的完成GoEasy消息的发送和接收,祝贺您!
更多详情,可以参考文档相关章节:
也可以在线咨询GoEasy技术支持。