1、在ucosII系統(tǒng)中創(chuàng)建一個進(jìn)程:
//TCP 2000
OSTaskCreate(tcp, (void *)0, &gstack_task_socket4[TASK_SOCKET4_STK_SIZE - 1], 14);
OSTaskNameSet(14, "tcp", &os_err);
2、進(jìn)程的具體處理:
void tcp(void *arg)
{
struct netconn *__pstConn, *__pstNewConn;
//建立TCP連接
__pstConn = netconn_new(NETCONN_TCP);
//將建立的連接進(jìn)行端口綁定
netconn_bind(__pstConn, NULL, 2000); //HTTP_PORT,80端口
//開始監(jiān)聽
netconn_listen(__pstConn);
while(1)
{
//接收外部來的連接
__pstNewConn = netconn_accept(__pstConn);
//具體處理函數(shù)
tcp_process(__pstNewConn);
//如果連接有效,刪除連接
if (__pstNewConn == NULL)
continue;
netconn_delete(__pstNewConn);
OSTimeDly(100);
}
具體處理函數(shù)如下:
void tcp_process(struct netconn *conn)
{
struct netbuf *inbuf;
char *rq;
u16_t len;
///獲取數(shù)據(jù)
inbuf = netconn_recv(conn);
if(inbuf != NULL)
{
netbuf_data(inbuf, &rq, &len);
/* HTTP "GET /\r\n" */
if(rq[0] == 'G' && rq[1] == 'E' && rq[2] == 'T') {
netconn_write(conn, http_html_hdr, sizeof(http_html_hdr),
NETCONN_NOCOPY);
//發(fā)送數(shù)據(jù)
netconn_write(conn, indexdata, sizeof(indexdata),
NETCONN_NOCOPY);
//netconn_write(conn,tcp_data_send,sizeof(tcp_data_send),NETCONN_NOCOPY);
//發(fā)送數(shù)據(jù)
netconn_close(conn); //與netconn_new對應(yīng)
//關(guān)閉連接
}
}
memp_free(MEMP_NETBUF, inbuf);
}
補(bǔ)充一點(diǎn),兩個數(shù)組的定義:
char indexdata1[] =
"<html> \
<head><title>Mr Lee's test page</title></head> \
<body> \
Hello , Mr Lee!\r\n \
Good Luck to you !\r\n \
This is a small test page. \
</body> \
</html>";
char http_html_hdr[] =
"HTTP/1.0 200 OK\r\n\
Content-type: text/html\r\n\r\n";