### Start, Stop, and Status Gateway-WebSocket Server
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.cn.md
Commands to manage the gateway-websocket server lifecycle, including starting, stopping, and checking its status. A 'reload' command for hot configuration updates is under development.
```Bash
go run ./main.go start // Start the gateway-websocket server
go run ./main.go stop // Stop the gateway-websocket server
go run ./main.go status // Check the gateway-websocket server running status
go run ./main.go reload // Hot update gateway-websocket configuration [feature under development]
```
--------------------------------
### Start, Stop, and Status Commands
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.md
Provides commands to manage the gateway-websocket server lifecycle, including starting, stopping, and checking its operational status. A 'reload' command for hot-reloading configuration is under development.
```bash
go run ./main.go start // Start the gateway-websocket server
go run ./main.go stop // Stop the gateway-websocket server
go run ./main.go status // Check the gateway-websocket server running status
go run ./main.go reload // Hot update gateway-websocket configuration [feature under development]
```
--------------------------------
### Gateway Websocket Client Operations
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/index.html
Demonstrates various operations related to managing clients in a gateway websocket system. This includes broadcasting messages to all clients, checking if a specific client is online, closing a client's connection, sending a message to a particular client, retrieving a list of all online clients, and counting the total number of online clients.
```Go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func main() {
http.HandleFunc("/ws", handleConnections)
log.Println("http server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Failed to upgrade to websocket: %v", err)
return
}
defer ws.Close()
// Example: Send a welcome message to the client
err = ws.WriteMessage(websocket.TextMessage, []byte("Welcome to the gateway!"))
if err != nil {
log.Printf("Error sending welcome message: %v", err)
return
}
// Example: Read messages from the client (simplified)
for {
_, message, err := ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("Read error: %v", err)
} else {
log.Printf("Client disconnected: %v", err)
}
break
}
log.Printf("%s", message)
// Example: Echo the message back to the client
err = ws.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Printf("Write error: %v", err)
break
}
}
}
// Placeholder functions for client operations (implementation details omitted)
// BroadcastMessage sends a message to all connected clients
func BroadcastMessage(message string) {
fmt.Printf("Broadcasting message: %s\n", message)
// Implementation to send message to all clients
}
// IsClientOnline checks if a client is currently connected
func IsClientOnline(clientID string) bool {
fmt.Printf("Checking if client %s is online\n", clientID)
// Implementation to check client status
return true // Placeholder
}
// CloseClientConnection closes the connection for a specific client
func CloseClientConnection(clientID string) {
fmt.Printf("Closing connection for client %s\n", clientID)
// Implementation to close client connection
}
// SendMessageToClient sends a message to a specific client
func SendMessageToClient(clientID string, message string) {
fmt.Printf("Sending message to client %s: %s\n", clientID, message)
// Implementation to send message to a specific client
}
// GetAllOnlineClients returns a list of all currently connected client IDs
func GetAllOnlineClients() []string {
fmt.Println("Getting all online clients")
// Implementation to get all online clients
return []string{"client1", "client2"} // Placeholder
}
// CountOnlineClients returns the total number of connected clients
func CountOnlineClients() int {
fmt.Println("Counting online clients")
// Implementation to count online clients
return 2 // Placeholder
}
```
--------------------------------
### Gateway Websocket UI Styling
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/index.html
Provides CSS styles for the gateway websocket user interface. It includes styles for layout, video boxes, buttons, and a logger for displaying messages and errors. The styles ensure a responsive and visually organized presentation of the websocket client.
```CSS
/* Basic reset and box-sizing */
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
/* Container for layout */
.container {
width: 100%;
display: flex;
display: -webkit-flex;
justify-content: space-around;
padding-top: 100px;
}
/* Styling for video display boxes */
.video-box {
position: relative;
width: 800px;
height: 400px;
}
/* Styling for the remote video feed */
#remote-video {
width: 100%;
height: 100%;
display: block;
object-fit: cover;
border: 1px solid #eee;
background-color: #F2F6FC;
}
/* Styling for the local video feed */
#local-video {
position: absolute;
right: 0;
bottom: 0;
width: 240px;
height: 120px;
object-fit: cover;
border: 1px solid #eee;
background-color: #EBEEF5;
}
/* Styling for the start button */
.start-button {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
line-height: 40px;
outline: none;
color: #fff;
background-color: #409eff;
border: none;
border-radius: 4px;
cursor: pointer;
transform: translate(-50%, -50%);
}
/* Styling for the message logger */
.logger {
width: 100%;
position: fixed;
bottom: 0;
height: 150px;
padding: 14px;
overflow-y: auto;
line-height: 1.5;
color: #4fbf40;
background-color: #272727;
}
/* Specific styling for error messages and timestamps in the logger */
.logger .error,
.error .time {
background-color: #DD4A68 !important;
color: #fff;
}
.logger .time {
background-color: yellow;
padding-left: 10px;
margin-right: 5px;
}
/* Styling for token display */
.token {
width: 100%;
color: #4fbf40;
background-color: #272727;
font-size: 18px;
padding: 10px;
}
.token .col-12 {
display: inline-block;
}
/* Styling for input fields within the token display */
.token input {
border-radius: 5px;
height: 30px;
width: 300px;
padding: 5px;
}
```
--------------------------------
### User and Client Management via WebSocket
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/index.html
Handles various user and client operations through WebSocket connections. Includes binding UIDs to clients, retrieving client information, checking online status, sending messages, and managing groups. Uses jQuery for DOM manipulation and AJAX calls.
```JavaScript
$(function(){
$('.getclientbyuid').on('click', function(){
var client = prompt('输入client');
if (client) {
$.post('getclientbyuid', { client: client }, function(res){
console.log(res);
});
}
});
$('.unbinduid').on('click', function(){
var client = prompt('输入client');
if (client) {
$.post('unbinduid', { client: client }, function(res){
console.log(res);
});
}
});
$('.uidisonline').on('click', function(){
var uid = prompt('输入Uid');
if (uid) {
$.post('uidisonline', { uid: uid }, function(res){
console.log(res);
});
}
});
$('.sendmessagetouid').on('click', function(){
var uid = prompt('输入Uid');
if (uid) {
var msg = prompt('输入消息内容');
if (msg) {
$.post('sendmessagetouid', { uid: uid, msg: msg }, function(res) {
console.log(res);
});
}
}
});
$('.getallonlineuid').on('click', function(){
$.post('getallonlineuid', {}, function(res) {
console.log(res);
});
});
$('.countonlineuid').on('click', function(){
$.post('countonlineuid', {}, function(res) {
console.log(res);
});
});
$('.getuidbyclient').on('click', function(){
var uid = prompt('输入要查询的uid');
if (uid) {
$.post('getuidbyclient', { uid: uid }, function(res) {
console.log(res);
});
}
});
$('.leavegroup').on('click', function(){
var group = prompt('输入群组名称');
if (group) {
var client = prompt('输入client编号');
if (client) {
$.post('leavegroup', { group: group, client: client }, function(res) {
console.log(res);
});
}
}
});
$('.getgrouponlineclient').on('click', function(){
var group = prompt('输入群组名称');
if (group) {
$.post('getgrouponlineclient', { group: group }, function(res) {
console.log(res);
});
}
});
$('.countgroup').on('click', function(){
$.post('countgroup', {}, function(res) {
console.log(res);
});
});
$('.countonlinegroup').on('click', function(){
var group = prompt('输入群组名称');
if (group) {
$.post('countonlinegroup', { group: group }, function(res) {
console.log(res);
});
}
});
$('.sendmessagetogroup').on('click', function(){
var group = prompt('输入群组名称');
if (group) {
var msg = prompt('输入消息内容');
if (msg) {
$.post('sendmessagetogroup', { group: group, msg: msg }, function(res) {
console.log(res);
});
}
}
});
$('.ungroup').on('click', function(){
var word = prompt('输入要解散的群组');
if (word) {
$.post('ungroup', { group: word }, function(res) {
console.log(res);
});
}
});
$('.countonlineclient').on('click', function(){
$.post('countonlineclient', {}, function(res) {
console.log(res);
});
});
$('.getallonlineclient').on('click', function(){
$.post('getallonlineclient', {}, function(res) {
console.log(res);
});
});
$('.sendmessagetoclient').on('click', function(){
var word = prompt('输入要接收消息的clientid');
if (word) {
$.post('sendmessagetoclient', { clientid: word }, function(res) {
console.log(res);
});
}
});
$('.clonseclient').on('click', function(){
var word = prompt('输入要关闭的clientid');
if (word) {
$.post('clonseclient', { clientid: word }, function(res) {
console.log(res);
});
}
});
$('.clientisonline').on('click', function(){
var word = prompt('输入要查询的clientid');
if (word) {
$.post('clientisonline', { clientid: word }, function(res) {
console.log(res);
});
}
});
$('.joingroup').on('click', function(){
var word = prompt('输入要绑定的群组编号');
if (word) {
$.post('joingroup', { clientid: $('b').text(), group: word }, function(res) {
console.log(res);
});
}
});
$('.clientbindiud').on('click', function(){
var word = prompt('输入要绑定的uid');
if (word) {
$.post('clientbindiud', { clientid: $('b').text(), uid: word }, function(res) {
console.log(res);
});
}
});
$('.broadcastmessage').on('click', function(){
var word = prompt('输入要广播的内容');
if (word) {
$.post('broadcastmessage', { msg : word }, function(res) {
console.log(res);
});
}
});
});
```
--------------------------------
### GatewayWebSocketClient Class
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/index.html
A JavaScript class for managing WebSocket connections to a gateway. It handles message reception, connection closing, and periodic 'ping' messages to maintain the connection. Includes a logging utility.
```JavaScript
class GatewayWebSocketClient {
constructor(socketUrl) {
this.ws = new WebSocket(socketUrl);
this.ws.onmessage = this.handleMessage.bind(this);
this.ws.onclose = this.handleClose.bind(this);
this.startPing();
this.dumpMsg = {
el: document.querySelector('.logger'),
log(msg, type = '') {
this.el.innerHTML += `${new Date().toLocaleTimeString()} > ${msg}
`;
this.el.scrollTop = this.el.scrollHeight;
},
};
}
handleMessage(event) {
this.dumpMsg.log(`收到内容 ${event.data}`);
}
handleClose(event) {
this.dumpMsg.log('ws连接已断开', 'error');
}
async wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async startPing() {
while (true) {
await this.wait(5000);
if (this.ws.readyState === WebSocket.OPEN) {
this.dumpMsg.log(`readyState${this.ws.readyState}, WebSocket.OPEN = ${WebSocket.OPEN}`);
this.ws.send('ping');
} else {
this.dumpMsg.log('WebSocket 未处于打开状态,无法发送心跳');
}
}
}
}
(function() {
const client = new GatewayWebSocketClient("ws://127.0.0.1:8282");
})();
```
--------------------------------
### Gateway Websocket Group Operations
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/index.html
Illustrates operations for managing groups within a gateway websocket system. This includes adding clients to groups, dissolving groups, sending messages to specific groups, counting online members in a group, counting the total number of groups, retrieving all online clients within a group, and removing clients from a group.
```Go
package main
import "fmt"
// Placeholder functions for group operations (implementation details omitted)
// AddClientToGroup adds a client to a specified group
func AddClientToGroup(clientID string, groupID string) {
fmt.Printf("Adding client %s to group %s\n", clientID, groupID)
// Implementation to add client to group
}
// DissolveGroup removes a group and all its members
func DissolveGroup(groupID string) {
fmt.Printf("Dissolving group %s\n", groupID)
// Implementation to dissolve group
}
// SendMessageToGroup sends a message to all clients in a specific group
func SendMessageToGroup(groupID string, message string) {
fmt.Printf("Sending message to group %s: %s\n", groupID, message)
// Implementation to send message to group
}
// CountOnlineMembersInGroup counts the number of online clients in a group
func CountOnlineMembersInGroup(groupID string) int {
fmt.Printf("Counting online members in group %s\n", groupID)
// Implementation to count online members in group
return 5 // Placeholder
}
// CountGroups counts the total number of existing groups
func CountGroups() int {
fmt.Println("Counting total groups")
// Implementation to count groups
return 10 // Placeholder
}
// GetAllOnlineClientsInGroup retrieves all online clients within a group
func GetAllOnlineClientsInGroup(groupID string) []string {
fmt.Printf("Getting all online clients in group %s\n", groupID)
// Implementation to get online clients in group
return []string{"clientA", "clientB"} // Placeholder
}
// RemoveClientFromGroup removes a client from a specified group
func RemoveClientFromGroup(clientID string, groupID string) {
fmt.Printf("Removing client %s from group %s\n", clientID, groupID)
// Implementation to remove client from group
}
```
--------------------------------
### Gateway-WebSocket gRPC API Documentation
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.cn.md
This section details the gRPC interfaces provided by gateway-websocket for inter-language communication. It covers operations related to clients, users, and groups, including message broadcasting, sending messages to specific entities, managing connections, and group operations.
```APIDOC
BroadcastMessage
- Purpose: Broadcasts a message to all clients.
- Category: client
SendMessageToClient
- Purpose: Sends a message to a specific client.
- Category: client
ClonseClient
- Purpose: Closes the connection of a specific client.
- Category: client
GetAllOnlineClient
- Purpose: Retrieves all currently online clients.
- Category: client
ClientIsOnline
- Purpose: Checks if a client is online.
- Category: client
CountOnlineClient
- Purpose: Counts the number of online clients.
- Category: client
UnGroup
- Purpose: Dissolves a specific group.
- Category: group
SendMessageToGroup
- Purpose: Sends a message to a specific group.
- Category: group
CountOnlineGroup
- Purpose: Counts the number of online clients within a group.
- Category: group
CountGroup
- Purpose: Counts the total number of groups.
- Category: group
GetGroupOnlineClient
- Purpose: Retrieves all online clients within a group.
- Category: group
LeaveGroup
- Purpose: Removes a client from a group.
- Category: group
JoinGroup
- Purpose: Adds a client to a group.
- Category: group
GetUidByClient
- Purpose: Retrieves all clients bound to a UID.
- Category: user
CountOnlineUid
- Purpose: Counts the number of online UIDs.
- Category: user
GetAllOnlineUid
- Purpose: Retrieves all online UIDs.
- Category: user
SendMessageToUid
- Purpose: Sends a message to all clients bound to a specific UID.
- Category: user
UidIsOnline
- Purpose: Checks if a UID exists.
- Category: user
UnBindUid
- Purpose: Unbinds a client from a UID.
- Category: user
ClientBindUid
- Purpose: Binds a client to a UID.
- Category: user
GetClientByUid
- Purpose: Retrieves the UID bound to a client.
- Category: user
```
--------------------------------
### gRPC API for User Management
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.md
Defines gRPC methods for managing user-client bindings and querying user-related information. This allows for associating clients with user IDs and sending messages targeted at specific users.
```APIDOC
GetUidByClient
- Retrieves all clients associated with a given User ID (UID).
CountOnlineUid
- Counts the number of online users (UIDs).
GetAllOnlineUid
- Retrieves a list of all online User IDs (UIDs).
SendMessageToUid
- Sends a message to all clients bound to a specific User ID (UID).
UidIsOnline
- Checks if a specific User ID (UID) is currently online.
UnBindUid
- Unbinds a client from its associated User ID (UID).
ClientBindUid
- Binds a client to a specific User ID (UID).
GetClientByUid
- Retrieves the User ID (UID) associated with a specific client.
```
--------------------------------
### gRPC API for Client Management
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.md
Defines gRPC methods for interacting with clients connected to the gateway-websocket server. These include broadcasting messages, sending messages to specific clients, closing client connections, and querying client status.
```APIDOC
BroadcastMessage
- Broadcasts a message to all connected clients.
SendMessageToClient
- Sends a message to a specific client.
ClonseClient
- Closes the connection for a specific client.
GetAllOnlineClient
- Retrieves a list of all currently online clients.
ClientIsOnline
- Checks if a specific client is currently online.
CountOnlineClient
- Returns the total count of online clients.
```
--------------------------------
### gRPC API for Group Management
Source: https://github.com/shawn-golang/gateway-websocket/blob/master/README.md
Provides gRPC methods for managing groups and message distribution within groups. This includes dissolving groups, sending messages to groups, and managing client membership in groups.
```APIDOC
UnGroup
- Dissolves a specified group.
SendMessageToGroup
- Sends a message to all clients within a specific group.
CountOnlineGroup
- Counts the number of online clients within a group.
CountGroup
- Counts the total number of existing groups.
GetGroupOnlineClient
- Retrieves all online clients belonging to a specific group.
LeaveGroup
- Removes a client from a group.
JoinGroup
- Adds a client to a group.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.