socket-connection.md 4.4 KB
Newer Older
S
shawn_he 已提交
1 2 3 4 5 6 7 8 9 10 11 12
# Socket Connection


## Use Cases

Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported.


## Available APIs

The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs.

13
| API| Description |
S
shawn_he 已提交
14
| -------- | -------- |
15 16 17
| constructUDPSocketInstance() | Creates a **UDPSocket** object. |
| constructTCPSocketInstance() | Creates a **TCPSocket** object. |
| bind() | Binds the IP address and port number. |
S
shawn_he 已提交
18
| send() | Sends data.|
19 20 21 22 23 24 25 26 27 28
| close() | Closes a Socket connection. |
| getState() | Obtains the Socket connection status. |
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. |
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. |
| on(type: 'message') | Enables listening for **message** events of the Socket connection. |
| off(type: 'message') | Disables listening for **message** events of the Socket connection. |
| on(type: 'close') | Enables listening for **close** events of the Socket connection. |
| off(type: 'close') | Disables listening for **close** events of the Socket connection. |
| on(type: 'error') | Enables listening for **error** events of the Socket connection. |
| off(type: 'error') | Disables listening for **error** events of the Socket connection. |
S
shawn_he 已提交
29 30 31
| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. |
32
| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. |
S
shawn_he 已提交
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


## How to Develop

The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example.

1. Import the required Socket module.

2. Create a **TCPSocket** object.

3. (Optional) Enable listening for TCPSocket events.

4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.

5. Set up a connection to the specified IP address and port number.

6. Send data.

7. Enable the TCPSocket connection to be automatically closed after use.
   
   ```js
   import socket from '@ohos.net.socket'
   
   // Create a TCPSocket object.
   let tcp = socket.constructTCPSocketInstance();
   
   // Enable listening for TCPSocket events.
   tcp.on('message', value => {
       console.log("on message")
       let buffer = value.message
       let dataView = new DataView(buffer)
       let str = ""
       for (let i = 0;i < dataView.byteLength; ++i) {
           str += String.fromCharCode(dataView.getUint8(i))
       }
Q
qingdao@qing 已提交
68
       console.log("on connect received:" + str)
S
shawn_he 已提交
69 70 71 72 73 74 75 76
   });
   tcp.on('connect', () => {
       console.log("on connect")
   });
   tcp.on('close', () => {
       console.log("on close")
   });
   
S
shawn_he 已提交
77
   // Bind the local IP address and port number.
S
shawn_he 已提交
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 120 121 122 123 124
   let bindAddress = {
       address: '192.168.xx.xx',
       port: 1234, // Bound port, for example, 1234.
       family: 1
   };
   tcp.bind(bindAddress, err => {
       if (err) {
           console.log('bind fail');
           return;
       }
       console.log('bind success');
       // Set up a connection to the specified IP address and port number.
       let connectAddress = {
           address: '192.168.xx.xx',
           port: 5678, // Connection port, for example, 5678.
           family: 1
       };
       tcp.connect({
           address: connectAddress, timeout: 6000
       }, err => {
           if (err) {
               console.log('connect fail');
               return;
           }
           console.log('connect success');
           // Send data.
           tcp.send({
               data: 'Hello, server!'
           }, err => {
               if (err) {
                   console.log('send fail');
                   return;
               }
               console.log('send success');
           })
       });
   });
   // Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
   setTimeout(() => {
       tcp.close((err) => {
           console.log('close socket.')
       });
       tcp.off('message');
       tcp.off('connect');
       tcp.off('close');
   }, 30 * 1000);
   ```