代码之家  ›  专栏  ›  技术社区  ›  programmerJavaPL

WebSocket连接

  •  1
  • programmerJavaPL  · 技术社区  · 6 年前

    如何在React Native中的应用程序和ASP.NET核心中的服务器之间建立WebSockets连接?

    react native中的当前信号器不适用于net core版本。

    是否需要在两侧使用干净的WebSocket?

    1 回复  |  直到 6 年前
        1
  •  0
  •   programmerJavaPL    6 年前

    发布的react本机信号库实际上不与net core一起工作。

    但解决方案在javascript客户机中 @aspnet/signalr 版本 1.0.3

    在服务器上,我们还安装 SignalR 在版本中 1.0.3

    双方必须兼容。

    移动应用程序侧面的使用示例:

    import React, {
        Component
    } from 'react'
    import {
        View
        , StyleSheet
        , Text
        , Button
    } from 'react-native'
    
    import * as signalR from '@aspnet/signalr';
    
    export default class Settings extends Component {
        constructor(props) {
            super(props);
    
            this.state = {
                message: 'No messages.'
            };
    
            this.messageReceived = this.messageReceived.bind(this);
    
            const hubUrl = 'http://10.0.2.2:62954/chat';
    
            const connectionHub = new signalR.HubConnectionBuilder()
                .withUrl(hubUrl)
                .configureLogging(signalR.LogLevel.Information)
                .build();
    
            connectionHub.on('ReceiveMessage', this.messageReceived);
            connectionHub.start()
                .catch(err => this.logError(err));
    
            this.connection = connectionHub;
        }
    
        messageReceived(message) {
            this.setState({
                message
            });
        }
    
        sendTestMessage() {
            this.connection.invoke('SendMessage', 'NameUser', 'Test message from mobile app.')
                .catch(err => this.logError(err));
        }
    
        render() {
            return (
                <View style={styles.container}>
                <View>
                    <Text>{this.state.message}</Text>
                </View>
                <View>
                    <Button title={"send"} onPress={this.sendTestMessage.bind(this)}>
                    </Button>
                </View>
            </View>
            )
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1
            , backgroundColor: '#0a3c63'
        , }
    , });
    

    信号文件建议的服务器站点