티스토리 뷰

HardWare/ARTIK

[ARTIK 050] TCP Server

White Whale 2016. 10. 26. 14:25
728x90

1. 개요

  ARTIK 050가 Server, 컴퓨터(C언어)가 Client가 되는 소스코드입니다. Server Code를 보시면 시나리오가 Client와 연결이 되면 문자열 데이터를 수신받고 받은 데이터를 다시 보내고, 소켓을 끊어버립니다. 이후 다시 다른 Client가 들어올 때까지 대기합니다.



2. Source Code(ARTIK) - TCP Server

 

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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#include "wiced.h"
 
#define TCP_PACKET_MAX_DATA_LENGTH          (30)
#define TCP_SERVER_LISTEN_PORT              (50007) //PORT
#define TCP_SERVER_THREAD_PRIORITY          (WICED_DEFAULT_LIBRARY_PRIORITY)
/* Stack size should cater for printf calls */
#define TCP_SERVER_STACK_SIZE               (6200)
#define TCP_SERVER_COMMAND_MAX_SIZE         (10)
#define TCP_PACKET_MAX_DATA_LENGTH          (30)
 
/* Keepalive will be sent every 2 seconds */
#define TCP_SERVER_KEEP_ALIVE_INTERVAL      (2)
/* Retry 10 times */
#define TCP_SERVER_KEEP_ALIVE_PROBES        (5)
/* Initiate keepalive check after 5 seconds of silence on a tcp socket */
#define TCP_SERVER_KEEP_ALIVE_TIME          (5)
#define TCP_SILENCE_DELAY                   (30)
 
typedef struct
{
    wiced_bool_t quit;
    wiced_tcp_socket_t socket;
}tcp_server_handle_t;
 
static void tcp_server_thread_main(uint32_t arg);
static wiced_result_t tcp_server_process(  tcp_server_handle_t* server, wiced_packet_t* rx_packet );
 
static const wiced_ip_setting_t device_init_ip_settings =
{
    INITIALISER_IPV4_ADDRESS( .ip_address, MAKE_IPV4_ADDRESS(192,168,  0,  1) ),
    INITIALISER_IPV4_ADDRESS( .netmask,    MAKE_IPV4_ADDRESS(255,255,255,  0) ),
    INITIALISER_IPV4_ADDRESS( .gateway,    MAKE_IPV4_ADDRESS(192,168,  0,  1) ),
};
 
static wiced_thread_t      tcp_thread;
static tcp_server_handle_t tcp_server_handle;
 
void application_start(void)
{
    wiced_interface_t interface;
    wiced_result_t result;
 
    /* Initialise the device and WICED framework */
    wiced_init( );
 
    /* Bring up the network interface */
    result = wiced_network_up_default( &interface, &device_init_ip_settings );
 
    while( result != WICED_SUCCESS )
    {
        printf("Bringing up network interface failed !\r\n");
        result = wiced_network_up_default( &interface, &device_init_ip_settings );
    }
 
    /* Create a TCP server socket */
    while (wiced_tcp_create_socket(&tcp_server_handle.socket, interface) != WICED_SUCCESS)
    {
        WPRINT_APP_INFO(("TCP socket creation failed\n"));
    }
 
    while (wiced_tcp_listen( &tcp_server_handle.socket, TCP_SERVER_LISTEN_PORT ) != WICED_SUCCESS)
    {
        WPRINT_APP_INFO(("TCP server socket initialization failed\n"));
    }
 
    /* Start a tcp server thread */
    WPRINT_APP_INFO(("Creating tcp server thread \n"));
    wiced_rtos_create_thread(&tcp_thread, TCP_SERVER_THREAD_PRIORITY, "Demo tcp server", tcp_server_thread_main, TCP_SERVER_STACK_SIZE, &tcp_server_handle);
 
}
 
static wiced_result_t tcp_server_process(  tcp_server_handle_t* server, wiced_packet_t* rx_packet )
{
    char*           request;
    uint16_t        request_length;
    uint16_t        available_data_length;
    wiced_packet_t* tx_packet;
    char*           tx_data;
 
    wiced_packet_get_data( rx_packet, 0, (uint8_t**) &request, &request_length, &available_data_length );
 
    /* Null terminate the received string */
    request[request_length] = '\x0';
    WPRINT_APP_INFO(("Received data: %s \n", request));
 
    /* Send echo back */
    if (wiced_packet_create_tcp(&server->socket, TCP_PACKET_MAX_DATA_LENGTH, &tx_packet, (uint8_t**)&tx_data, &available_data_length) != WICED_SUCCESS)
    {
        WPRINT_APP_INFO(("TCP packet creation failed\n"));
        return WICED_ERROR;
    }
 
    /* Write the message into tx_data"  */
    memcpy(tx_data, request, request_length);
    tx_data[request_length] = '\x0';
 
    /* Set the end of the data portion */
    wiced_packet_set_data_end(tx_packet, (uint8_t*)tx_data + request_length);
 
    /* Send the TCP packet */
    if (wiced_tcp_send_packet(&server->socket, tx_packet) != WICED_SUCCESS)
    {
        WPRINT_APP_INFO(("TCP packet send failed\n"));
 
        /* Delete packet, since the send failed */
        wiced_packet_delete(tx_packet);
 
        server->quit=WICED_TRUE;
        return WICED_ERROR;
    }
    WPRINT_APP_INFO(("Echo data: %s\n", tx_data));
 
    return WICED_SUCCESS;
}
 
static void tcp_server_thread_main(uint32_t arg)
{
    tcp_server_handle_t* server = (tcp_server_handle_t*) arg;
 
    while ( server->quit != WICED_TRUE )
    {
        wiced_packet_t* temp_packet = NULL;
 
        /* Wait for a connection */
        wiced_result_t result = wiced_tcp_accept( &server->socket );
 
#ifdef TCP_KEEPALIVE_ENABLED
        result = wiced_tcp_enable_keepalive(&server->socket, TCP_SERVER_KEEP_ALIVE_INTERVAL, TCP_SERVER_KEEP_ALIVE_PROBES, TCP_SERVER_KEEP_ALIVE_TIME );
        if( result != WICED_SUCCESS )
        {
            WPRINT_APP_INFO(("Keep alive initialization failed \n"));
        }
#endif /* TCP_KEEPALIVE_ENABLED */
 
        if ( result == WICED_SUCCESS )
        {
            /* Receive the query from the TCP client */
            if (wiced_tcp_receive( &server->socket, &temp_packet, WICED_WAIT_FOREVER ) == WICED_SUCCESS)
            {
                /* Process the client request */
                tcp_server_process( server, temp_packet );
 
                /* Delete the packet, we're done with it */
                wiced_packet_delete( temp_packet );
 
#ifdef TCP_KEEPALIVE_ENABLED
                WPRINT_APP_INFO(("Waiting for data on a socket\n"));
                /* Check keepalive: wait to see whether the keepalive protocol has commenced */
                /* This is achieved by waiting forever for a packet to be received on the TCP connection*/
                if (wiced_tcp_receive( &server->socket, &temp_packet, WICED_WAIT_FOREVER ) == WICED_SUCCESS)
                {
                    tcp_server_process( server, temp_packet );
                    /* Release the packet, we don't need it any more */
                    wiced_packet_delete( temp_packet );
                }
                else
                {
                    WPRINT_APP_INFO(("Connection has been dropped by networking stack\n\n"));
                }
#endif /* TCP_KEEPALIVE_ENABLED */
 
            }
            else
            {
                /* Send failed or connection has been lost, close the existing connection and */
                /* get ready to accept the next one */
                wiced_tcp_disconnect( &server->socket );
            }
        }
    }
    WPRINT_APP_INFO(("Disconnect\n"));
 
    wiced_tcp_disconnect( &server->socket );
 
    WICED_END_OF_CURRENT_THREAD( );
}



3. Souce Code(PC) - TCP Client

  파라메터는 <Server IP> <port> 2개 입력해 주시면 됩니다.

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
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#pragma comment(lib, "Ws2_32.lib")
#define BUF_SIZE 100
 
 
int main(int argc, char **argv) {
    WSADATA wsaData;
    struct sockaddr_in server_addr;
    SOCKET s;
 
    if (argc != 3) {
        printf("Command parameter does not right.\n");
        exit(1);
    }
 
    WSAStartup(MAKEWORD(2, 2), &wsaData);
 
    if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        printf("Socket Creat Error.\n");
        exit(1);
    }
 
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));
 
    if (connect(s, (SOCKADDR *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
        printf("Socket Connection Error.\n");
        exit(1);
    }
 
    printf("Connect Complete\n");
 
    char *msg = "ping";
    int sendBytes;
    sendBytes = send(s, msg, sizeof(msg), 0);
    printf("Send message : %s\n", msg);
 
    char buf[BUF_SIZE];
    int recvBytes;
    recvBytes = recv(s, buf, BUF_SIZE, 0);
    printf("Recv message : %s\n", buf);
 
    closesocket(s);
    WSACleanup();
 
    return 0;
}



4. 결과


 



5. 소스 저장소


'HardWare > ARTIK' 카테고리의 다른 글

[ARTIK 050] LIS3DH(가속도 센서)  (0) 2016.10.26
[ARTIK 050] TCP Client  (0) 2016.10.26
[ARTIK 050] USB UART  (7) 2016.10.25
[ARTIK 050] Thread  (0) 2016.10.17
[ARTIK 050] RGB LED(LS5050RGB, KY-009)  (0) 2016.10.17
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함