-
说明
-
点击数:1915
#include "vxWorks.h"
#include "sockLib.h"
#include "inetLib.h"
#include "stdioLib.h"
#include "strLib.h"
#include "hostLib.h"
#include "ioLib.h"
//#include "tcpExample.h"
#define SERVER_PORT_NUM 5001
#define SERVER_WORK_PRIORITY 100
#define SERVER_STACT_SIZE 10000
#define SERVER_MAX_CONNECTIONS 4
#define REQUEST_MSG_SIZE 1024
#define REPLY_MSG_SIZE 500
#define ERROR (-1)
int tcp_server(void)
{
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
char rcvBuf[REQUEST_MSG_SIZE];
int sockAddrSize;
int sFd;
int newFd;
int nByte;
//1 create socket
if((sFd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
{
printf("create socket error!\n");
return ERROR;
}
//2 init some parameter
sockAddrSize=sizeof(struct sockaddr_in);
bzero((char *)&serverAddr, sockAddrSize);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT_NUM);
serverAddr.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddr.sin_len=(unsigned char)sockAddrSize;
//3 bind socket
if(bind(sFd,(struct sockaddr*)(&serverAddr),sockAddrSize)== ERROR)
{
printf("bind error!\n");
close(sFd);
return ERROR;
}
//3 listen client
if(listen(sFd,SERVER_MAX_CONNECTIONS) == ERROR)
{
printf("listen error!\n");
close(sFd);
return ERROR;
}
//下面可以使用死循环或线程创建accept,并创建相对应的接收线程
//4.accept server
newFd = accept(sFd,(struct sockaddr*)(&clientAddr),&sockAddrSize);
printf("server get connection from %s\n",inet_ntoa(clientAddr.sin_addr));
while(1)
{
//5.receive
nByte = recv(newFd, rcvBuf, REQUEST_MSG_SIZE, 0);//收不到数据阻塞
rcvBuf[nByte] = '\0';
printf("server received datas : %s\n", rcvBuf);
if(rcvBuf[0]=='q')
break;
}
//6.close *Fd
close(newFd);
close(sFd);
return 0;
}
int tcp_client(char * serverName)
{
struct sockaddr_in serverAddr;
char sendBuf[REQUEST_MSG_SIZE];
int sockAddrSize;
int sFd;
//1 create socket
if((sFd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
{
printf("create socket error!\n");
return ERROR;
}
//2 init some parameter
sockAddrSize=sizeof(struct sockaddr_in);
bzero((char *)&serverAddr, sockAddrSize);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT_NUM);
serverAddr.sin_len=(unsigned char)sockAddrSize;
if((serverAddr.sin_addr.s_addr = inet_addr(serverName))== ERROR &&
(serverAddr.sin_addr.s_addr = hostGetByName(serverName)) == ERROR)
{
printf("unknown serverName\n");
close(sFd);
return ERROR;
}
//3 connnect server
if(connect(sFd,(struct sockaddr*)(&serverAddr),sockAddrSize) == ERROR)
{
printf("connect error\n");
return ERROR;
}
//4:send datas to server
printf("please input chars:\n");
//send(sFd,sendBuf, strlen(sendBuf), 0);
while(1){
fgets(sendBuf,REQUEST_MSG_SIZE,stdin);
write(sFd,sendBuf, strlen(sendBuf));
if(sendBuf[0] == 'q')
break;
}
//5 close sFd
close(sFd);
return 0;
}