SRS streaming media service (3) SRS service http(s) api operation SRS service

SRS streaming media server provides a powerful API for developers to customize their own streaming media services according to their own business scenarios.

Local environment:

Virtual machine VMPRO15 installs Linux system: CentOS7

SRS service version: SRSv4-b2-4.0.215 (SRSv4 has officially released a stable version in December 2021)

Linux opens ports and services:

 Linux network environment: 192.168.5.104 

Physical machine local network environment: 192.168.5.101

1. To test the http api provided by the SRS service, you first need to enable the corresponding service in the SRS configuration file:

2. Access API:

2.1. SRS provides api breadcrumbs, which can be navigated from the root directory without any memory. Common fields include:

  • code indicates the error code, according to the Linux convention, 0 indicates success.
  • urls means breadcrumb navigation, the sub-api (link) under this api.
  • data indicates the API that provides services at the last level, and the returned data.

2.2. Use Postman to request the top API provided by SRS (http://192.168.5.104:1985):

2.3. Visit the next-level API again (http://192.168.5.104:1985/api):

 2.4. Continue reading (http://192.168.5.104:1985/api/v1):

2.5. Try to get the connected client information of the SRS server (http://192.168.5.104:1985/api/v1/clients): 

 

 

2.6, SRS HTTP API supports cross-domain, js can directly call the http api of srs.

SRS supports two cross-domain methods:

  • OPTIONS: jquery can directly request the API across domains, and the browser will send an OPTIONS cross-domain request. After SRS allows cross-domain, the browser initiates the API request again.
  • JSONP: jquery/angularjs can initiate a JSONP cross-domain request, and the server will respond as a js file, the content is to call a function, and the function name is specified by the callback in the QueryString.
  • JSONP-DELETE: JSONP can only be GET, so the DELETE method is specified by the method of QueryString.

2.7. SRS has built-in support for https_api, you only need to enable https in the configuration (replace the certificate with your own certificate)

http_api {
    enabled         on;
    listen          1985;
    https {
        #是否开启https
        enabled on;
        #监听端口号
        listen 1990;
        #SSL私钥文件
        #       openssl genrsa -out server.key 2048
        # default: ./conf/server.key
        key ./conf/server.key;
        # SSL公共证书
        #       openssl req -new -x509 -key server.key -out server.crt -days 3650 -subj "/C=CN/ST=Beijing/L=Beijing/O=Me/OU=Me/CN=ossrs.net"
        # default: ./conf/server.crt
        cert ./conf/server.crt;
    }
}

2.8. All APIs and descriptions provided by SRS (may be inaccurate due to continuous version updates):

3. The interface test kicks off the client connected to the SRS server

 Test to kick off the client connected to SRS through the API provided by SRS. First, a GET request (http://192.168.5.104:1985/api/v1/clients) is required to obtain all client information, get the client ID, and then pass The DELETE request (http://192.168.5.104:1985/api/v1/clients/clientID) kicks off the client. If you only kick the streaming client, you can get the streaming terminal through the API (http://192.168.5.104:1985 /api/v1/streams), where streams.publish.cid is the streaming client ID number.

3.1. Use HBuilderX to create a uniapp project, create index and live 2 pages, use the uniapp official UI components uni-table and uni-popop, install it directly through the HBuilderX plug-in mall, and use the uniapp official streaming plug-in live-pusher Realize video capture and streaming

The UI components are as follows:

 

index.view

<template>
    <view>
        <live-pusher class="livePusher-top" id="livePusher" @statechange="statechange"  :beauty="beauty" :whiteness="whiteness"  :url="url" :enable-camera="enableCamera" mode="FHD"></live-pusher>
        <button v-if="flag" @click="startLive">开始直播</button>
        <button v-if="!flag" @click="stopLive">结束直播</button>
		<button  @click="pauseLive">暂停直播</button>
		<button  @click="resumeLive">恢复直播</button>
		<view class="uni-title">美颜</view>
		<slider min="0" max="9" value="0" @change="sliderChangeBeauty" activeColor="#FFCC33" backgroundColor="#000000" block-color="#8A6DE9" block-size="20" show-value />
		<view class="uni-title">美白</view>
		<slider min="0" max="9" value="0" @change="sliderChangeWhiteness" activeColor="#FFCC33" backgroundColor="#000000" block-color="#8A6DE9" block-size="20" show-value />
		
		<uni-popup ref="popup" :mask-click="false" type="message">
			<uni-popup-message  type="warn" :message="message" :duration="0"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	export default {
        data() {
            return {
                url: 'rtmp://192.168.5.104/live/1',//推流地址
                enableCamera: true,//开启摄像头
                context: null,
				beauty : 0,//美颜值
				whiteness : 0 ,//美白值
				flag : true,
				message : null,//提示消息
				date : null,//定义时间
				dateStr : null
            };
        },
        onReady() {
            this.context = uni.createLivePusherContext('livePusher', this);
            // this.context.switchCamera() // 摄像头切换(切换为后置)
			setTimeout(()=>{
				this.context.startPreview() // 摄像头预览 (不加会黑屏)
			},1000);
            
        },
        methods: {
			//开始推流
            startLive() {
                this.context.start({
                    success: (res) => {
						this.flag=!this.flag;
                        console.log('livePusher.start:' + JSON.stringify(res));
                    },
					fail: (err)=>{
						console.log("livePusher失败:"+JSON.stringify(err));
					},
					complete:(res)=>{
						console.log("livePusher执行完成:"+JSON.stringify(res));
					}
                });
            },
			//停止推流
            stopLive() {
                this.context.stop({
                    success: (res) => {
						this.flag=!this.flag;
                        console.log('livePusher.stop:'+JSON.stringify(res));
						this.context.stopPreview(); // 关闭摄像头预览
                    }
                });
            },
			//暂停推流
			pauseLive(){
				this.context.pause({
					success: (res)=>{
						console.log('livePusher.pause:'+JSON.stringify(res));
					}
				});
				
			},
			//恢复推流
			resumeLive(){
				this.context.resume({
					success: (res)=>{
						console.log('livePusher.resume:'+JSON.stringify(res));
					}
				});
			},
			//设置美颜
			sliderChangeBeauty(e){
				this.beauty = e.detail.value;
				console.log("美颜值改变"+e.detail.value);
			},
			//设置美白
			sliderChangeWhiteness(e){
				this.whiteness = e.detail.value;
				console.log("美白值改变"+e.detail.value);
			},
			//状态改变数据,部分状态码如下:
			//1001:连接RTMP服务器成功
			//1002:RTMP开始推流
			//1003:打开摄像头成功
			//1007:首帧画面采集完成
			//1008:启动硬编
			//1101:上行带宽不足,数据发送不及时
			//1102:启动网络重连
			//3004:UNKNOWN
			//3005:tcp通道发送失败 错误码[-4]
			//-1307:所有IP都已经尝试失败,可以放弃治疗
			statechange(e){
				console.log("状态"+e.detail.code+e.detail.message);
				if(e.detail.code==3005){//TCP通道断开
				this.date = new Date();
				this.dateStr = this.date.getFullYear()+":"
							+this.date.getMonth()+1+":"
							+this.date.getDate()+":"
							+this.date.getHours()+":"
							+this.date.getMinutes()+":"
							+this.date.getSeconds();
					this.flag = true;
					this.message = this.dateStr+"网络断开,正在重新连接";
					this.open();
				}if(e.detail.code==1102){//启动网络重连
					
				}if(e.detail.code==1001){//已经连接RTMO服务器
					// this.close();
					// this.message = "已连接服务器";
					// this.open();
					
				}if(e.detail.code==1002){//RTMP开始推流
					this.flag = false;
					this.close();
				}if(e.detail.code==-1307){//重连失败
					this.close();
					this.message = "重连失败";
					this.open();
				}
			},
			open() {
			        this.$refs.popup.open('top')
			},
			close() {
			        this.$refs.popup.close()
			}
			
        }
	}

</script>

<style>
.livePusher-top{
	background-color:white;
	
}
</style>

live.vue

<template>
	<view>
		<uni-table border stripe emptyText="暂无更多数据" >
		    <!-- 表头行 -->
		    <uni-tr>
		        <uni-th  align="center">客户端ID</uni-th>
		        <uni-th  align="center">客户端IP</uni-th>
		        <uni-th  align="center">类型</uni-th>
				<uni-th  align="center">操作</uni-th>
		    </uni-tr>
		    <!-- 表格数据行 -->
		    <uni-tr v-for="(list,index) in liveList">
		        <uni-td align="center">{
   
   {list.id}}</uni-td>
		        <uni-td align="center">{
   
   {list.ip}}</uni-td>
		        <uni-td align="center">{
   
   {list.type}}</uni-td>
				<uni-td align="center">
					<button @click="tichu(list.id,index)" class="mini-btn" type="warn" size="mini">踢出</button>
				</uni-td>
		    </uni-tr>
		    
		
		</uni-table>
		
	</view>
</template>

<script>
	
	export default {
		data() {
			return {
				//定义客户端列表
				liveList : null,
			}
		},
		onReady() {
			// 每秒更新客户端列表数据
			setInterval(()=>{
				uni.request({
					url:"http://192.168.5.104:1985/api/v1/clients",
					success: (res) => {
							this.liveList = res.data.clients;
					    },
					fail: (err) =>{
						console.log(err.data);
						console.log("失败");
					}
				})
			},1000)
			
		},
		methods: {
			tichu(clientID,index){
				uni.request({
					url:"http://192.168.5.104:1985/api/v1/clients/"+clientID,
					method:'DELETE',
					success: (res) => {
							if(res.data.code==0){
								this.liveList.splice(index,1);
							}
					    },
					fail: (err) =>{
						console.log(err.data);
						console.log("失败");
					}
				})
			}
		}
	}
</script>

<style>

</style>

3.2. SRS service configuration, open http_api service, open RTC service, open RTMP to RTC stream, later use RTMP protocol to push stream, RTC protocol to pull stream (play)

 

 

 

3.3. After the page is written, it can be run directly. Open HBuilderX to connect to the mobile phone, run it on the real machine, and start live broadcast (push streaming).

 

 3.4. Use Google Chrome to open http://192.168.5.104:8080 and use RTC player to pull the stream (RTC protocol has low playback delay)

 3.5. Use HBuilderX to run to the browser—Chrome, open the live broadcast center, and kick out the client.

 The page shows 2 clients (GET request http://192.168.5.104:1985/api/v1/clients), one pusher and one puller.

Screenshot of GIF on the PC side (the image quality is hard to describe, but CSDN does not support video uploading), kicked in about 32 seconds, and the push stream on the mobile phone was disconnected and reconnected, so it will automatically reconnect after being kicked out of the push end The screen freezes after streaming, and moves again after reconnecting.

 

 Mobile Screenshot

 From the above, we can see that the client is successfully kicked out by operating the SRS service through http_api.

 

Guess you like

Origin blog.csdn.net/weixin_44341110/article/details/122516644