forked from Rapsssito/react-native-tcp-socket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
119 lines (99 loc) · 3.02 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { init, server, client } from './examples/echo';
class App extends React.Component {
/**
* @param {any} props
*/
constructor(props) {
super(props);
this.updateChatter = this.updateChatter.bind(this);
this.state = { chatter: [] };
}
/**
* @param {string | Error} msg
*/
updateChatter(msg) {
console.log(msg);
this.setState({
// @ts-ignore
chatter: this.state.chatter.concat([msg]),
});
}
componentDidMount() {
server.on('connection', (socket) => {
this.updateChatter('Client connected to server on ' + JSON.stringify(socket.address()));
socket.on('data', (data) => {
this.updateChatter('Server client received: ' + (data.length < 500 ? data : data.length + ' bytes'));
});
socket.on('error', (error) => {
this.updateChatter('Server client error ' + error);
});
socket.on('close', (error) => {
this.updateChatter('Server client closed ' + (error ? error : ''));
});
});
server.on('error', (error) => {
this.updateChatter(error);
this.updateChatter('Server error ' + error);
});
server.on('close', () => {
this.updateChatter('Server closed');
});
client.on('connect', () => {
this.updateChatter('Opened client on ' + JSON.stringify(client.address()));
});
client.on('drain', () => {
this.updateChatter('Client drained');
});
client.on('data', (data) => {
this.updateChatter('Client received: ' + (data.length < 500 ? data : data.length + ' bytes'));
});
client.on('error', (error) => {
this.updateChatter('Client error ' + error);
});
client.on('close', (error) => {
this.updateChatter('Client closed ' + (error ? error : ''));
});
init();
}
render() {
return (
<View style={styles.container}>
<ScrollView>
{this.state.chatter.map((msg, index) => {
return (
<Text key={index} style={styles.welcome}>
{msg}
</Text>
);
})}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default App;