📄 smtcp.c
字号:
#include <io.h>
#include <Winsock.h>
#include <stdlib.h>
#include "vscp_os.h"
#include "iblock.h"
#include "smctimer.h"
#include "spsms.h"
#include "./coding/coding.h"
fd_set m_readset;
#define SOCK_BUF_SIZE 1024
#define ISMGPORT 7890
extern int SendToMesq(void * ptr);
char g_sSpID[8];
char g_sSpPWD[8];
void OnCMPPClientConnected(int sock,char *sIpAddr,unsigned short nPort)
{
unsigned char * ptr ;
ptr = GetIdleBlock(32,M_SPSMS_C);
if(ptr == NULL)
{
printf("OnCMPPClientConnected Alloc Mem Error !!\n");
return ;
}
*(unsigned short *)(ptr+0) = SMCPP|1;
*(unsigned int *)(ptr+2) = sock;
SendToMesq(ptr);
}
void OnCMPPClientDisconnected(int sock)
{
unsigned char * ptr ;
ptr = GetIdleBlock(32,M_SPSMS_C);
if(ptr == NULL)
{
printf("OnCMPPClientConnected Alloc Mem Error !!\n");
return ;
}
*(unsigned short *)(ptr+0) = SMCPP|2;
*(unsigned int *)(ptr+2) = sock;
SendToMesq(ptr);
}
SOCKET ClientStart(char * ip,unsigned short port)
{
struct sockaddr_in dest;
unsigned int sock;
unsigned long flag = 0;
sock = socket(PF_INET,SOCK_STREAM,0);
if(sock < 0)
{
int err = WSAGetLastError();
return -1;
}
memset(&dest,0, sizeof(dest));
dest.sin_family = PF_INET;
dest.sin_port = htons(port);
dest.sin_addr.S_un.S_addr = inet_addr(ip);
while(1)
{
if(0 != connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
{
closesocket(sock);
sock = socket(PF_INET,SOCK_STREAM,0);
if(sock < 0)
{
int err = WSAGetLastError();
return -1;
}
}
else
{
OnCMPPClientConnected(sock,ip,port);
printf("ISMG connect ok !\n");
break;
}
ThreadSleep(2000);
}
return sock;
}
void RecvIsmgMsg(unsigned char * buf, unsigned short nLen)
{
unsigned char * ptr ;
ptr = GetIdleBlock(nLen+16,M_SPSMS_C);
if(ptr == NULL || buf == NULL)
{
printf("RecvIsmg error message !!");
return ;
}
//*Test by spirit
printf("%h", buf);
//*/
*(unsigned short *)(ptr+0) = SMCPP|0;
*(unsigned short *)(ptr+2) = nLen;
memcpy((ptr+4),buf,nLen);
SendToMesq(ptr);
}
void RecvClient(SOCKET sock,char * ip,unsigned short port)
{
int rlen;
struct timeval timeout = {0,0};
unsigned char buf[1024];
int arg=0;
ioctlsocket(sock,FIONBIO,&arg);
rlen = recv (sock, buf, 1024, 0);
if (rlen > 0)
{
RecvIsmgMsg(buf,(unsigned short)rlen);
}
else
{
OnCMPPClientDisconnected(sock);
}
return ;
}
void * ClientThread(void *papa)
{
SOCKET sock;
do
{
if(SpSmc.state != SPSMC_ISMGOK)
{
sock = ClientStart(SpSmc.localip,ISMGPORT);
if (sock != -1)
{
RecvClient(sock,SpSmc.localip,ISMGPORT);
}
}
RecvClient(sock,SpSmc.localip,ISMGPORT);
Sleep(10);
} while (1);
}
void StartClient()
{
ThreadCreat(0, ClientThread, NULL, 0, 0);
}
int SendMsg(unsigned int sock,char * sBuf,int nLen)
{
int ret = send(sock,sBuf,nLen,MSG_DONTROUTE);
if(ret == nLen)
return 0;
else
{
OnCMPPClientDisconnected(sock);
closesocket(sock);
return 104;
}
}
void CloseClient()
{
OnCMPPClientDisconnected(SpSmc.sock);
closesocket(SpSmc.sock);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -