📄 tcpserver.c
字号:
/*includes*/
#include "tcpExample.h"
/*function declares*/
void tcpServerWorkTask(int sFd, char * address, u_short port);
void tcpServer(void);
/*start tcp server task*/
extern void dosock(void)
{
taskSpawn("tcpServer",100,0,8*1024,(void *)tcpServer,0,0,0,0,0,0,0,0,0,0);
}
void tcpServer(void)
{
struct sockaddr_in serverAddr, clientAddr;
int sFd, newFd;
int sockAddrSize;
int ix = 0; /*count for task spawned by server*/
char workName[16]; /*name of task spawned by server*/
/*initialize the local settings*/
sockAddrSize = sizeof (struct sockaddr_in);
bzero((char *)&serverAddr,sockAddrSize);
serverAddr.sin_family = AF_INET;
serverAddr.sin_len = (u_char)sockAddrSize;
serverAddr.sin_port = htons (TCP_PORT);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
printf("TCP Server test begin!!\n");
/*create a TCP socket*/
if((sFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket error\n");
return;
}
/*bind the socket to local address*/
if (bind (sFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
printf("bind error\n");
close(sFd);
return;
}
/*create the client connection request queue*/
if (listen (sFd, SERVER_MAX_CONNECTIONS) < 0)
{
printf("listen error\n");
close(sFd);
return;
}
/*accept new connection request and spawn a new task to deal with the request*/
for(; ;)
{
/*display information of the whole running tasks with 2 seconds delay*/
taskDelay(2000);
taskinfo();
if((newFd = accept(sFd, (struct sockaddr *)&clientAddr, &sockAddrSize)) < 0)
{
printf("accept error\n");
close(sFd);
return;
}
printf("ACCEPTED:%s\n", inet_ntoa(clientAddr.sin_addr));
sprintf(workName, "tTcpWork%d",ix++);
/*spawn task to communicate with client*/
if (taskSpawn(workName,100,0,8*1024,(void *)tcpServerWorkTask,newFd,
(int)inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port),0,0,0,0,0,0,0)<0)
{
printf("taskspawn error\n");
close(newFd);
};
}
}
void tcpServerWorkTask(int sFd, char * address, u_short port)
{
char msg[MSG_SIZE];
int nRead;
static char replyMsg[] = "Server received your message";
/*read the client's request and display it*/
while((nRead = read (sFd, msg, sizeof(msg) ))> 0) /*blocked until message arrive*/
{
printf("MESSAGE FROM CLIENT (Internet Address %s,port %d):\n%s\n",
address,port,msg);
memset(msg,0,sizeof(msg));
free (address);
if (write(sFd,replyMsg,sizeof(replyMsg)) < 0)
printf("write error\n");
}
/*when server or client close the socket fd,nRead will be below zero*/
if (nRead < 0)
printf("read error\n"); /*this maybe not display on the screen*/
close(sFd); /*task is over & it will be deleted by system*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -