#include
#include
#include
#include
#include "NC_ComLib.h"
SOCKET m_sock;
int NetTimeout =8000 ;//网络超时时间
void Com_Hook_DebugOutHex( unsigned char *data, unsigned int datalen )
{
unsigned int i=0;
for(i =0; i < datalen; i++)
{
printf("%02x",data[i]);
}
printf("\r\n");
}
void Com_Hook_DebugOutAscii( unsigned char *data, unsigned int datalen )
{
printf("%s\n",data);
}
int Connect( const char* address,int port)
{
int rlt = 0;
int iErrMsg;
//初始化WinSock
WSADATA wsaData;
iErrMsg = WSAStartup(MAKEWORD(2,2),&wsaData);
if (iErrMsg != 0)
{
printf("failed with wsaStartup error : %d\n",iErrMsg);
rlt = 1;
return rlt;
}
m_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (m_sock == INVALID_SOCKET)
{
printf("socket failed with error : %d\n",WSAGetLastError());
rlt = 2;
return rlt;
}
//地址配置
SOCKADDR_IN sockaddrServer;
sockaddrServer.sin_family = AF_INET;
sockaddrServer.sin_port = htons(port);
sockaddrServer.sin_addr.s_addr = inet_addr(address);
setsockopt(m_sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&NetTimeout,sizeof(int));
//建立连接
iErrMsg = connect(m_sock,(SOCKADDR*)&sockaddrServer,sizeof(sockaddrServer));
if (iErrMsg < 0)
{
printf("connect failed with error : %d\n",iErrMsg);
rlt = 3;
return rlt;
}
return rlt;
}
int SendMsg(const char* msg,int len)
{
int rlt = 0;
int iErrMsg = 0;
iErrMsg = send(m_sock,msg,len,0);
if (iErrMsg < 0)
{
printf("send msg failed with error : %d\n",iErrMsg);
rlt = 1;
return rlt;
}
return rlt;
}
unsigned int Com_Dev_Connect( const char* address,int port, unsigned int timeout,unsigned int channel )
{
return Connect(address,port);
}
unsigned int Com_Dev_TxData( unsigned char *buf, unsigned int len, unsigned int timeout, unsigned int channel )
{
unsigned int rlt = 0;
int iErrMsg = 0;
iErrMsg = send(m_sock,(char*)buf,len,0);
if (iErrMsg < 0)
{
printf("send msg failed with error : %d\n",iErrMsg);
rlt = 1;
return rlt;
}
printf("->send:\r\n");
Com_Hook_DebugOutAscii(buf,len);
return rlt;
}
unsigned int Com_Dev_RxData( unsigned char *buf, unsigned int *len, unsigned int bufsize, unsigned int timeout, unsigned int channel )
{
unsigned int rcode = 0;
int rval = 0;
unsigned char recvbuf[bufsize];
rval = recv(m_sock,(char*)recvbuf,bufsize,0);
if(rval == SOCKET_ERROR)
{
printf("recv socket error!\r\n");
rcode = rval;
}
else if (rval == 0)
{
//recv·µ»Ø0±íʾÕý³£Í˳ö
printf("ending connection!\r\n");
rcode =200;
}
else
{
//ÏÔʾ½ÓÊÕµ½µÄÊý¾Ý
printf("
*len = rval;
memcpy(buf,recvbuf,*len);
Com_Hook_DebugOutAscii(buf,*len);
rcode =0;
}
return rcode;
}
unsigned int Com_Dev_Disconnect( unsigned int channel )
{
closesocket(m_sock);
return 0;
}
编译环境是windows下的GCC编译器 minGW
makefile 如下:
######################################## #makefile ######################################## BINARY= libmytcp CC= gcc LD= ld CFLAGS= -std=c99 LDSCRIPT= -lws2_32 LDFLAGS= -Llib OBJS= NC_ComLib.o #CFLAGS=-std=c99 .PHONY: clean all:images images: $(BINARY).a $(OBJS):%.o:%.c $(CC) -c $(CFLAGS) $< -o $@ %.a: $(OBJS) ar crv $(*).a $(OBJS) clean: rm -f *.o