Files

163 lines
3.3 KiB
JavaScript

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
TextInput,
} from 'react-native';
import IPCSocket from 'react-native-ipc';
export default class IpcExample extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
servertext: '',
isStart: false,
isConnect: false,
};
}
onStartPressed = () => {
IPCSocket.startServer((error, response) => {
if (error) {
console.error(error);
} else {
this.setState({isStart: response});
console.log(this.state.isStart);
}
})
}
onStopPressed = () => {
IPCSocket.stopServer((error, response) => {
if (error) {
console.error(error);
} else {
this.setState({isStart: !response});
console.log(this.state.isStart);
}
})
}
onConnectPressed = () => {
IPCSocket.connectClient((error, response) => {
if (error) {
console.error(error);
} else {
this.setState({isConnect: response});
console.log(this.state.isConnect);
}
})
}
onDisconnectPressed = () => {
IPCSocket.disconnectClient((error, response) => {
if (error) {
console.error(error);
} else {
this.setState({isConnect: !response});
console.log(this.state.isConnect);
}
})
}
onSendMessagePressed = () => {
IPCSocket.messageToServer({ name: 'key', cmd: this.state.text }, (error, response) => {
if (error) {
console.error(error);
} else {
this.setState({servertext: response});
console.log(this.state.servertext);
}
})
}
renderStartButton() {
if (this.state.isStart) {
return (
<Button
onPress= {this.onStopPressed}
title = "Stop Server"
/>
);
} else {
return (
<Button
onPress= {this.onStartPressed}
title = "Start Server"
/>
);
}
}
renderConnectButton() {
if (this.state.isConnect) {
return (
<Button
onPress= {this.onDisconnectPressed}
title = "Disconnect Client"
/>
);
} else {
return (
<Button
onPress= {this.onConnectPressed}
title = "Connect Client"
/>
);
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.button}>
{this.renderStartButton()}
{this.renderConnectButton()}
<TextInput
style={styles.textinput}
placeholder="Type here to send!"
onChangeText={(text) => this.setState({text})}
/>
<Button
onPress= {this.onSendMessagePressed}
title = "Send Message"
/>
<Text style={{padding: 10, fontSize: 24}}>
{this.state.servertext}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
backgroundColor: '#F5FCFF',
},
button: {
marginTop: 10,
height: 40,
marginHorizontal: 12,
},
textinput: {
marginTop: 10,
height: 40,
marginHorizontal: 12,
borderColor: 'black',
borderWidth: 1,
},
});
AppRegistry.registerComponent('IpcExample', () => IpcExample);