vxworks下socket编程 TCP 通信

35 篇文章 22 订阅

vxworks 下socket编程 TCP 通信头文件 

#ifndef  _INC_TCPSOCKET_H
#define  _INC_TCPSOCKET_H

 

#ifdef  _cplusplus

   extern   "C"  {

#endif
    
#include<stdio.h>
#include <stdLib.h>
    
#define SERVER_PORT_NUM 5432 /* server's port number for bind() */
#define SERVER_WORK_PRIORITY 100 /* priority of server's work task */
#define SERVER_STACK_SIZE 10000 /* stack size of server's work task */
#define SERVER_MAX_CONNECTIONS 4 /* max clients connected at a time */
#define REQUEST_MSG_SIZE 1024 /* max size of request message */
#define REPLY_MSG_SIZE 500 /* max size of reply message */
/* structure for requests from clients to server */
    
    
   
struct request
{
int reply; /* TRUE = request reply from server */
int msgLen; /* length of message text */
char message[REQUEST_MSG_SIZE]; /* message buffer */
};

 


#ifdef __cplusplus
}
#endif
   
#endif



vxworks下socket编程 TCP 通信服务器端 . 

#ifndef  _INC_TCPSOCKET_SERVER_H
#define  _INC_TCPSOCKET_SERVER_H

 

#ifdef  _cplusplus

   extern   "C"  {

#endif
    
#include "vxWorks.h"
#include "sockLib.h"
#include "inetLib.h"     //inet_
#include "in.h"     //包含sockaddr
#include "taskLib.h"
#include "stdioLib.h"
#include "strLib.h"
#include "ioLib.h"
#include "fioLib.h"
#include "tcpsocket.h"

/* function declarations */
VOID tcpServerWorkTask (int sFd, char * address, u_short port);
/****************************************************************************
*
* tcpServer - accept and process requests over a TCP socket
*
* This routine creates a TCP socket, and accepts connections over the socket
* from clients. 【Each client connection is handled by spawning a separate
* task to handle client requests.】
*
* This routine may be invoked as follows:
* -> sp tcpServer
* task spawned: id = 0x3a6f1c, name = t1
* value = 3829532 = 0x3a6f1c
* -> MESSAGE FROM CLIENT (Internet Address 150.12.0.10, port 1027):
* Hello out there
*
* RETURNS: Never, or ERROR if a resources could not be allocated.
*/


typedef  int STATUS  ;

 

STATUS tcpServer (void)
{

struct sockaddr_in serverAddr; 
struct sockaddr_in clientAddr;

int sockAddrSize; 
int sFd; 
int newFd;
int ix = 0;
char workName[16];

/* set up the local address */
sockAddrSize = sizeof (struct sockaddr_in);
bzero ((char *) &serverAddr, sockAddrSize);
//memset(void *)&serverAddr,0, sockAddrSize);

serverAddr.sin_family = AF_INET;
//serverAddr.sin_len = (u_char) sockAddrSize;
serverAddr.sin_port = htons (SERVER_PORT_NUM);
//serverAddr.sin_port = htons (0);  /*----看下这样配置是什么效果---*/

serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);   /*---server  上的任意地址---*/

//serverAddr.sin_addr.s_addr = htonl ("10.168.7.1");

/* create a TCP-based socket */
if ((sFd = socket (AF_INET, SOCK_STREAM, 0)) == ERROR)    /*---这里有个flag 可以设置---*/
{
     printf("creat socket error\n");
  
      return (ERROR);
}
/* bind socket to local address */
if (bind (sFd, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR)
{
        printf("server bind error\n");
        close (sFd);  /*---绑定失败要关掉socket-----*/
     return (ERROR);
}

/* create queue for client connection requests */
if (listen (sFd, SERVER_MAX_CONNECTIONS) == ERROR)      /*---一次监听4个---*/
{
    printf("listen error\n");
     close (sFd);
      return (ERROR);
}
/* accept new connect requests and spawn tasks to process them */


FOREVER
{

  /*--accept  成功会返回一个新的socket id ,原来的id  继续监听链路上的要求---*/
if ((newFd = accept (sFd, (struct sockaddr *) &clientAddr,   /*----这里保存客户端的地址,但是并没有初始化---*/
&sockAddrSize)) == ERROR)
{
    printf("accept error\n");
    close (sFd);
    return (ERROR);
}

# if 0
else
{
   /*--这里打印下客户端的地址信息,验证下----*/
 printf("client sockaddress info :\n");
    printf("client address : %s\t   port  %d\n ",inet_ntoa (clientAddr.sin_addr),ntohs (clientAddr.sin_port));

     /*---端口号是50043,ip地址是“10.168.7.1”----*/  
    
     /*----这里还说明了客户端和服务器端的端口号是不同的,基于不同的端口发消息---*/
}

#endif

sprintf (workName, "tTcpWork%d", ix++);
printf("workName %s\n",workName);

if (taskSpawn(workName, SERVER_WORK_PRIORITY, 0, SERVER_STACK_SIZE,
(FUNCPTR) tcpServerWorkTask, newFd,
(int) inet_ntoa (clientAddr.sin_addr), ntohs (clientAddr.sin_port),   /*---终于明白了,这里的三个参数传递---*/
0, 0, 0, 0, 0, 0, 0) == ERROR)
{
/* if taskSpawn fails, close fd and return to top of loop */
    printf("tcptask creat failed\n");
    close (newFd);
}
}
}

#if 0

/****************************************************************************
*
* tcpServerWorkTask - process client requests
*
* This routine reads from the server's socket, and processes client
* requests. If the client requests a reply message, this routine
* will send a reply to the client.
*
* RETURNS: N/A.
*/

VOID tcpServerWorkTask
(
int sFd, /* server's socket fd */
char * address, /* client's socket address */
u_short port /* client's socket port */
)
{


char recvbuf[2048];

int recvbytes;


while(1)
{

  recvbytes= recv(sFd, recvbuf, sizeof(recvbuf), 0);

   recvbuf[recvbytes-1]='\0';

   if (recvbytes!=0)
    {
       printf("server recv msg  len %d\n",recvbytes);
    
          printf("msg content  %s\n",recvbuf);
    }
  

   break;
   
  
}
   
   
   
}


#endif

 

 

/****************************************************************************
*
* tcpServerWorkTask - process client requests
*
* This routine reads from the server's socket, and processes client
* requests. If the client requests a reply message, this routine
* will send a reply to the client.
*
* RETURNS: N/A.
*/
VOID tcpServerWorkTask
(
int sFd, /* server's socket fd */
char * address, /* client's socket address */
u_short port /* client's socket port */
)
{

struct request clientRequest; /* request/message from client */
int nRead; /* number of bytes read */
//static char replyMsg[] = "Server received your message";
static  char replyMsg[]="hello,client";
/* read client request, display message */

char recvbuf[2048];

int recvbytes;


while ((nRead = fioRead (sFd, (char *) &clientRequest,
sizeof (clientRequest))) > 0)
{
printf ("MESSAGE FROM CLIENT (Internet Address %s, port %d):\n%s\n",
address, port, clientRequest.message);
if (clientRequest.reply)
if (write (sFd, replyMsg, sizeof (replyMsg)) == ERROR)
perror ("write");
}
if (nRead == ERROR) /* error from read() */
perror ("read");
close (sFd); /* close server socket connection */


}

#ifdef __cplusplus
}
#endif
   
#endif


vxworks下socket编程TCP 客户端  

#ifndef  _INC_TCPSOCKET_CLIENT_H
#define  _INC_TCPSOCKET_CLINET_H

 

#ifdef  _cplusplus

   extern   "C"  {

#endif
   

/*----4.10 基于TCP 的客户端和服务器在板子上顺利调通----
 * 
 *  server 是个永久任务,人工启动之后挂起,接收到 client
 *  
 *  的请求后发出响应
 * 
 * 
 * 
 * *************************************************/    
   

/* tcpClient.c - TCP client example */
/*
DESCRIPTION
This file contains the client-side of the VxWorks TCP example code.
The example code demonstrates the usage of several BSD 4.4-style
socket routine calls.
*/
/* includes */
#include "vxWorks.h"
#include "sockLib.h"
#include "inetLib.h"
#include "stdioLib.h"
#include "strLib.h"
#include "hostLib.h"
#include "ioLib.h"
#include  "tcpsocket.h"
/****************************************************************************
*
* tcpClient - send requests to server over a TCP socket
*
* This routine connects over a TCP socket to a server, and sends a
* user-provided message to the server. Optionally, this routine
* waits for the server's reply message.
*
* This routine may be invoked as follows:
* -> tcpClient "remoteSystem"
* Message to send:
* Hello out there
* Would you like a reply (Y or N):
* y
* value = 0 = 0x0
* -> MESSAGE FROM SERVER:
* Server received your message
*
* RETURNS: OK, or ERROR if the message could not be sent to the server.
Wind River VxWorks Platforms
Getting Started, 3.8
42
*/
STATUS tcpClient
(
char * serverName /* name or IP address of server */
)
{
struct request myRequest; /* request to send to server */
struct sockaddr_in serverAddr; /* server's socket address */
char replyBuf[REPLY_MSG_SIZE]; /* buffer for reply */
char reply; /* if TRUE, expect reply back */
int sockAddrSize; /* size of socket address structure */
int sFd; /* socket file descriptor */
int mlen; /* length of message */
/* create client's socket */

 

if ((sFd = socket (AF_INET, SOCK_STREAM, 0)) == ERROR)
{
    printf("socket client error\n");
   return (ERROR);
}
/* bind not required - port number is dynamic */


/* build server socket address */

  /*---填充server 地址---*/
sockAddrSize = sizeof (struct sockaddr_in);
bzero ((char *) &serverAddr, sockAddrSize);
serverAddr.sin_family = AF_INET;
serverAddr.sin_len = (u_char) sockAddrSize;
serverAddr.sin_port = htons (SERVER_PORT_NUM);

if (((serverAddr.sin_addr.s_addr = inet_addr (serverName)) == ERROR) &&
((serverAddr.sin_addr.s_addr = hostGetByName (serverName)) == ERROR))
{
   printf("get server address error\n"); 
   
close (sFd);
return (ERROR);
}
/* connect to server */
if (connect (sFd, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR)
{
       printf("connet to server error \n");
    
       close (sFd);
       return (ERROR);
}


/* build request, prompting user for message */
printf ("Message to send: \n");
mlen = read (STD_IN, myRequest.message, REQUEST_MSG_SIZE);    /*-------------这个要注意----------------*/
myRequest.msgLen = mlen;
myRequest.message[mlen - 1] = '\0';
printf ("Would you like a reply (Y or N): \n");
read (STD_IN, &reply, 1);
switch (reply)
{
case 'y':
case 'Y': myRequest.reply = TRUE;
break;
default: myRequest.reply = FALSE;
break;
}
/* send request to server */
if (write (sFd, (char *) &myRequest, sizeof (myRequest)) == ERROR)    /*---这里用的是read ,write 接口---*/
{
    printf("write error\n");
 
     close (sFd);
return (ERROR);
}


if (myRequest.reply) /* if expecting reply, read and display it */
{
if (read (sFd, replyBuf, REPLY_MSG_SIZE) < 0)
{
       printf("read error\n");
close (sFd);
return (ERROR);
}
printf ("MESSAGE FROM SERVER:\n%s\n", replyBuf);
}
close (sFd);
return (OK);
}


#ifdef __cplusplus
}
#endif
#endif


vxworks的线程及互斥锁 

vxworks5.5开始支持POSIX线程实时扩展

vxworks本质只包括系统和任务两个概念,线程以任务形式实现。线程不属于任何进程,只属于整个系统,因而pthread在整个系统范围内竞争。

<1>vxworks任务在同一实地址空间运行,无任何保护机制,任何任务可以直接访问其他任务数据,POSIX中进程共享相关函数未实现。

<2>vxworks无用户和组概念,无进程概念。


创建 pthread_create

等待 ptherad_join

退出 pthread_exit

[cpp]  view plain copy
  1. #include<pthread.h>    
  2. #include<stdio.h>    
  3. #include<errno.h>   
  4. #include<unistd.h>   
  5. /*线程1*/  
  6. void thread1() {  
  7.     int i=0;  
  8.   
  9.     while (1) {  
  10.         printf("thread1:%d\n", i);  
  11.         if (i>3)  
  12.             pthread_exit(0);  
  13.         i++;  
  14.         sleep(1);  
  15.     }  
  16. }  
  17.   
  18. /*线程2*/  
  19. void thread2() {  
  20.     int i=0;  
  21.   
  22.     while (1) {  
  23.         printf("thread2:%d\n", i);  
  24.         if (i>5)  
  25.             pthread_exit(0);  
  26.         i++;  
  27.         sleep(1);  
  28.     }  
  29. }  
  30. int taskDemo() {  
  31.     pthread_t t1, t2;  
  32.     /*创建线程*/  
  33.     pthread_create(&t1, NULL, (void *)thread1, NULL);  
  34.     pthread_create(&t2, NULL, (void *)thread2, NULL);  
  35.     /*等待线程退出*/  
  36.     pthread_join(t1, NULL);  
  37.     pthread_join(t2, NULL);  
  38.     return 0;  
  39. }  
[cpp]  view plain  copy
  1. #include<pthread.h>   
  2. #include<stdio.h>   
  3. #include<errno.h>  
  4. #include<unistd.h>  
  5. /*线程1*/  
  6. void thread1() {  
  7.     int i=0;  
  8.   
  9.     while (1) {  
  10.         printf("thread1:%d\n", i);  
  11.         if (i>3)  
  12.             pthread_exit(0);  
  13.         i++;  
  14.         sleep(1);  
  15.     }  
  16. }  
  17.   
  18. /*线程2*/  
  19. void thread2() {  
  20.     int i=0;  
  21.   
  22.     while (1) {  
  23.         printf("thread2:%d\n", i);  
  24.         if (i>5)  
  25.             pthread_exit(0);  
  26.         i++;  
  27.         sleep(1);  
  28.     }  
  29. }  
  30. int taskDemo() {  
  31.     pthread_t t1, t2;  
  32.     /*创建线程*/  
  33.     pthread_create(&t1, NULL, (void *)thread1, NULL);  
  34.     pthread_create(&t2, NULL, (void *)thread2, NULL);  
  35.     /*等待线程退出*/  
  36.     pthread_join(t1, NULL);  
  37.     pthread_join(t2, NULL);  
  38.     return 0;  
  39. }  

运行

thread1:0
thread2:0
thread1:1
thread2:1
thread1:2
thread2:2
thread1:3
thread2:3
thread1:4
thread2:4
thread2:5
thread2:6

 

互斥锁

 互斥锁的操作主要包括以下几个步骤。
· 互斥锁初始化:pthread_mutex_init
· 互斥锁上锁:pthread_mutex_lock
· 互斥锁判断上锁:pthread_mutex_trylock
· 互斥锁接锁:pthread_mutex_unlock
· 消除互斥锁:pthread_mutex_destroy

[cpp]  view plain copy
  1. #include<pthread.h>   
  2. #include<stdio.h>    
  3. #include<errno.h>     
  4. #include<unistd.h>   
  5. int i=0;/*共享变量*/  
  6. static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;/*互斥锁*/  
  7.   
  8. void thread1() {  
  9.     int ret;  
  10.   
  11.     while (1) {  
  12.   
  13.         ret=pthread_mutex_trylock(&mutex);/*判断上锁 ret==0 */  
  14.   
  15.         if (ret!=EBUSY) {  
  16.             pthread_mutex_unlock(&mutex);/*解锁*/  
  17.             pthread_mutex_lock(&mutex);/*上锁*/  
  18.             printf("This is thread1:%d\n", i);  
  19.             i++;  
  20.             pthread_mutex_unlock(&mutex);/*解锁*/  
  21.         }  
  22.         sleep(1);  
  23.     }  
  24. }  
  25.   
  26. void thread2() {  
  27.     int ret;  
  28.     while (1) {  
  29.         ret=pthread_mutex_trylock(&mutex);  
  30.         if (ret!=EBUSY) {  
  31.             pthread_mutex_unlock(&mutex);/*解锁*/  
  32.             pthread_mutex_lock(&mutex);  
  33.             printf("This is thread2:%d\n", i);  
  34.             i++;  
  35.             pthread_mutex_unlock(&mutex);  
  36.         }  
  37.         sleep(1);  
  38.     }  
  39. }  
  40. int taskDemo() {  
  41.     pthread_t t1, t2;  
  42.     pthread_mutex_init(&mutex,NULL);  
  43.     pthread_create(&t1, NULL, (void *)thread1, NULL);  
  44.     pthread_create(&t2, NULL, (void *)thread2, NULL);  
  45.   
  46.     pthread_join(t1, NULL);  
  47.     pthread_join(t2, NULL);  
  48.     pthread_mutex_destroy(&mutex);  
  49.     return 0;  
  50. }  
[cpp]  view plain  copy
  1. #include<pthread.h>  
  2. #include<stdio.h>   
  3. #include<errno.h>    
  4. #include<unistd.h>  
  5. int i=0;/*共享变量*/  
  6. static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;/*互斥锁*/  
  7.   
  8. void thread1() {  
  9.     int ret;  
  10.   
  11.     while (1) {  
  12.   
  13.         ret=pthread_mutex_trylock(&mutex);/*判断上锁 ret==0 */  
  14.   
  15.         if (ret!=EBUSY) {  
  16.             pthread_mutex_unlock(&mutex);/*解锁*/  
  17.             pthread_mutex_lock(&mutex);/*上锁*/  
  18.             printf("This is thread1:%d\n", i);  
  19.             i++;  
  20.             pthread_mutex_unlock(&mutex);/*解锁*/  
  21.         }  
  22.         sleep(1);  
  23.     }  
  24. }  
  25.   
  26. void thread2() {  
  27.     int ret;  
  28.     while (1) {  
  29.         ret=pthread_mutex_trylock(&mutex);  
  30.         if (ret!=EBUSY) {  
  31.             pthread_mutex_unlock(&mutex);/*解锁*/  
  32.             pthread_mutex_lock(&mutex);  
  33.             printf("This is thread2:%d\n", i);  
  34.             i++;  
  35.             pthread_mutex_unlock(&mutex);  
  36.         }  
  37.         sleep(1);  
  38.     }  
  39. }  
  40. int taskDemo() {  
  41.     pthread_t t1, t2;  
  42.     pthread_mutex_init(&mutex,NULL);  
  43.     pthread_create(&t1, NULL, (void *)thread1, NULL);  
  44.     pthread_create(&t2, NULL, (void *)thread2, NULL);  
  45.   
  46.     pthread_join(t1, NULL);  
  47.     pthread_join(t2, NULL);  
  48.     pthread_mutex_destroy(&mutex);  
  49.     return 0;  
  50. }  


This is thread1:0
This is thread2:1
This is thread1:2
This is thread2:3
This is thread1:4
This is thread2:5
This is thread1:6
This is thread2:7
This is thread1:8
This is thread2:9
This is thread1:10


vxworks网络通信socket-TCP  

  1. /*Socket基础 
  2.  * A与B发送消息 
  3.  * */  
  4. #include<stdio.h>   
  5.   
  6. #include<taskLib.h>   
  7. #include<unistd.h>   
  8. #include<sockLib.h>   
  9. #include<netinet/in.h>   
  10. #include<inetLib.h>   
  11. #include<string.h>   
  12. #define TASK_PRIORITY_A 130   
  13. #define TASK_PRIORITY_B 130   
  14. #define STACK_SIZE 225   
  15. #define PORT 3733   
  16. int taskId_A, taskId_B;  
  17.   
  18. /*定义两个Task*/  
  19. void taskA(void);  
  20. void taskB(void);  
  21.   
  22. /*服务器ip地址*/  
  23. char ip[]="127.0.0.1";  
  24. /*服务端地址与客户端地址*/  
  25. struct sockaddr_in serAddr, cliAddr;  
  26. int len=sizeof(struct sockaddr_in);  
  27.   
  28. int taskDemo() {  
  29.   
  30.     /*创建任务:taskSpawn创建并激活任务*/  
  31.     taskId_A=taskSpawn("taskA", TASK_PRIORITY_A, VX_FP_TASK, STACK_SIZE,  
  32.             (FUNCPTR)taskA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);  
  33.     taskId_B=taskSpawn("taskB", TASK_PRIORITY_B, VX_FP_TASK, STACK_SIZE,  
  34.             (FUNCPTR)taskB, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);  
  35.     if (taskId_A==ERROR)  
  36.         printf("taskA taskSpawn() failed!\n");  
  37.     if (taskId_B==ERROR)  
  38.         printf("taskB taskSpawn() failed!\n");  
  39.   
  40. }  
  41.   
  42. /*服务端*/  
  43. void taskA() {  
  44.     int sockFd, newFd;  
  45.     char msg[]="hello";  
  46.   
  47.     /*创建套接字*/  
  48.     sockFd=socket(AF_INET,SOCK_STREAM,0);  
  49.   
  50.     /**************************************************************** 
  51.      * 设置套接字要绑定的网络地址,通过对结构体struct sockaddr_in seraddr赋值*/  
  52.     serAddr.sin_family=AF_INET;/*协议族 为ip协议族*/  
  53.     serAddr.sin_port=PORT;/*端口号*/  
  54.     inet_aton(ip, &(serAddr.sin_addr));/*将ip地址转为32位整数*/  
  55.     memset(serAddr.sin_zero, 0, 8);  
  56.     /****************************************************************/  
  57.     /*socket与地址绑定*/  
  58.     bind(sockFd, (struct sockaddr*)&serAddr, len);  
  59.    /*监听*/  
  60.     listen(sockFd, 10);  
  61.    /*接受连接*/  
  62.     newFd=accept(sockFd, (struct sockaddr *)&cliAddr, &len);  
  63.   
  64.     printf("[server]Get connect!\n");  
  65.    /*发送消息*/  
  66.     write(newFd, msg, sizeof(msg));  
  67.   
  68.     printf("[Server]Send message!\n");  
  69. }  
  70.   
  71. /*客户端*/  
  72. void taskB() {  
  73.     int sockFd, rLen;  
  74.     char buf[100];  
  75.     /*创建socket*/  
  76.     sockFd=socket(AF_INET,SOCK_STREAM,0);  
  77.     /*连接*/  
  78.     if (connect(sockFd, (struct sockaddr*)&serAddr, len)==OK)  
  79.         printf("[client]Connected\n");  
  80.     memset(buf, 0, 100);  
  81.    /*读取消息*/  
  82.     rLen=read(sockFd, buf, 255);  
  83.     buf[rLen]='\0';  
  84.     printf("[client]Get message:%s\n", buf);  
  85. }  
[cpp]  view plain  copy
  1. /*Socket基础 
  2.  * A与B发送消息 
  3.  * */  
  4. #include<stdio.h>  
  5.   
  6. #include<taskLib.h>  
  7. #include<unistd.h>  
  8. #include<sockLib.h>  
  9. #include<netinet/in.h>  
  10. #include<inetLib.h>  
  11. #include<string.h>  
  12. #define TASK_PRIORITY_A 130  
  13. #define TASK_PRIORITY_B 130  
  14. #define STACK_SIZE 225  
  15. #define PORT 3733  
  16. int taskId_A, taskId_B;  
  17.   
  18. /*定义两个Task*/  
  19. void taskA(void);  
  20. void taskB(void);  
  21.   
  22. /*服务器ip地址*/  
  23. char ip[]="127.0.0.1";  
  24. /*服务端地址与客户端地址*/  
  25. struct sockaddr_in serAddr, cliAddr;  
  26. int len=sizeof(struct sockaddr_in);  
  27.   
  28. int taskDemo() {  
  29.   
  30.     /*创建任务:taskSpawn创建并激活任务*/  
  31.     taskId_A=taskSpawn("taskA", TASK_PRIORITY_A, VX_FP_TASK, STACK_SIZE,  
  32.             (FUNCPTR)taskA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);  
  33.     taskId_B=taskSpawn("taskB", TASK_PRIORITY_B, VX_FP_TASK, STACK_SIZE,  
  34.             (FUNCPTR)taskB, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);  
  35.     if (taskId_A==ERROR)  
  36.         printf("taskA taskSpawn() failed!\n");  
  37.     if (taskId_B==ERROR)  
  38.         printf("taskB taskSpawn() failed!\n");  
  39.   
  40. }  
  41.   
  42. /*服务端*/  
  43. void taskA() {  
  44.     int sockFd, newFd;  
  45.     char msg[]="hello";  
  46.   
  47.     /*创建套接字*/  
  48.     sockFd=socket(AF_INET,SOCK_STREAM,0);  
  49.   
  50.     /**************************************************************** 
  51.      * 设置套接字要绑定的网络地址,通过对结构体struct sockaddr_in seraddr赋值*/  
  52.     serAddr.sin_family=AF_INET;/*协议族 为ip协议族*/  
  53.     serAddr.sin_port=PORT;/*端口号*/  
  54.     inet_aton(ip, &(serAddr.sin_addr));/*将ip地址转为32位整数*/  
  55.     memset(serAddr.sin_zero, 0, 8);  
  56.     /****************************************************************/  
  57.     /*socket与地址绑定*/  
  58.     bind(sockFd, (struct sockaddr*)&serAddr, len);  
  59.    /*监听*/  
  60.     listen(sockFd, 10);  
  61.    /*接受连接*/  
  62.     newFd=accept(sockFd, (struct sockaddr *)&cliAddr, &len);  
  63.   
  64.     printf("[server]Get connect!\n");  
  65.    /*发送消息*/  
  66.     write(newFd, msg, sizeof(msg));  
  67.   
  68.     printf("[Server]Send message!\n");  
  69. }  
  70.   
  71. /*客户端*/  
  72. void taskB() {  
  73.     int sockFd, rLen;  
  74.     char buf[100];  
  75.     /*创建socket*/  
  76.     sockFd=socket(AF_INET,SOCK_STREAM,0);  
  77.     /*连接*/  
  78.     if (connect(sockFd, (struct sockaddr*)&serAddr, len)==OK)  
  79.         printf("[client]Connected\n");  
  80.     memset(buf, 0, 100);  
  81.    /*读取消息*/  
  82.     rLen=read(sockFd, buf, 255);  
  83.     buf[rLen]='\0';  
  84.     printf("[client]Get message:%s\n", buf);  
  85. }  


运行

[client]Connected
[server]Get connect!
[Server]Send message!
[client]Get message:hello


vxworks 下select 机制 

vxworks下select()的使用  

2008-05-20 13:19:24|  分类: 嵌入系统 |  标签: |字号 订阅

select()作用是挂起一系列的文件描述符,其API为:

int select
    (
    int              width,      /* number of bits to examine from 0 */
    fd_set *         pReadFds,   /* read fds */
    fd_set *         pWriteFds, /* write fds */
    fd_set *         pExceptFds, /* exception fds (unsupported) */
    struct timeval * pTimeOut    /* max time to wait, NULL = forever */
    )
该函数允许一个任务挂起一系列的文件描述符,直到文件描述符已经准备好时,再将其唤醒。参数pReadFdspWriteFds, and pExceptFds 分别指向相应的文件描述符,每一个 bit对应一个文件描述符。pReadFds置位将会使select() 挂起读文件描述符,直到相应的文件描述符有数据准备好时才释放。同样pWriteFds将会引起写文件描述符发生相关的操作。pExceptFds在vxworks中没有用到。

下边的一些宏用于设置fd_set()

    FD_SET(fd, &fdset)
    FD_CLR(fd, &fdset)
    FD_ZERO(&fdset)

width为设置的bit数,可以是最大文件描述符数+1,或者FD_SETSIZE。当函数select返回时,将准备好的文件描述符对应的bit 置位,其他的清0。可以使用FD_ISSET 来检查那些被置位。

例: vxworks下基于select的tcp服务器端设计

#include <vxworks.h>
#include <sockLib.h>
#include <inetLib.h>
#include <MyServer.h>

#define DEFAULT_SERVER_PORT   6699
int server;
SEM_ID Server_SM;
/*
* Start the function Server() as a task in AppInit() like this:
* int ret = 0;
* ret = taskSpawn("tServer", 165, 0x0002, 1024,(FUNCPTR) Server, 
*                                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); 
*/
void Server()
{
    int rc = 0,sd = 0;
    int addr_len = 0; 
    int server_sock = 0;
    struct sockaddr_in server_addr,client_addr;
    
    memset(&server_addr,0,sizeof(struct sockaddr_in));
    memset(&client_addr,0,sizeof(struct sockaddr_in));
    server_sock = socket(AF_INET,SOCK_STREAM,0);
    if(server_sock < 0)
    {
    printf("Failed to create Socket.\n"); 
        return;
    }
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(DEFAULT_SERVER_PORT);
    rc = bind(server_sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr_in));
    if(rc == -1)
    {
    close(server_sock);
    printf("Failed to bind socket\n");
    return;
    }
    rc = listen(server_sock,2);
    if(rc == -1)
    {
    printf("socket listen error\n");
    return;
    }   
    printf("TCP server is ready for receive connection request\n");
    while(1)
    {
        addr_len = sizeof(struct sockaddr_in);
    sd = accept(server_sock,(struct sockaddr *)&client_addr,&addr_len);
    if(sd <= 0)
    {
         printf("socket accept error\n");
         return;
    }
    else
    {
         printf("Socket connect success\n");
         server = sd;
         server_proc(sd);
    }
    }
}
     
void server_proc(int sock)
{
    int rc = 0;
    char buffer[32];
    fd_set socket;
    struct timeval wait;
    
    wait.tv_sec = 0;
    wait.tv_usec = 500000;
    
    while(server > 0)
    {
    FD_ZERO(&socket);
    FD_SET(sock,&socket);
    
    rc = select(FD_SETSIZE,&socket,(fd_set *)0,(fd_set *)0,&wait);
    if(rc == 0)
         continue;
    if(FD_ISSET(sock,&socket))
    {
         semTake(Server_SM, WAIT_FOREVER);
         memset(buffer,0,sizeof(buffer));
         rc = recv(sock,buffer,sizeof(buffer),0);
         if(rc > 0)
         {
         /* you can add your application specific code here */
             printf("RecvMsg:%s\n",buffer);
             semGive(Server_SM);
         }
         else
         {
         printf("Socket closed\n");
         close(sock);
         server = 0;
         semGive(Server_SM);
         break;
         }
    }   
    taskDelay(10);
    }
     
}

/* end of the file */


  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值