当前位置: 首页 > 工具软件 > C Script > 使用案例 >

plc c脚本(c script) socket通信

鄂慈
2023-12-01

client 

#include "apdefap.h"
void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
// WINCC:TAGNAME_SECTION_START
// syntax: #define TagNameInAction "DMTagName"
// next TagID : 1
// WINCC:TAGNAME_SECTION_END


// WINCC:PICNAME_SECTION_START
// syntax: #define PicNameInAction "PictureName"
// next PicID : 1
// WINCC:PICNAME_SECTION_END




// Include header files
  #include "WSOCK32.h"


  #define PORT 8888
  #define SERVER_IP "192.168.30.119"
  // Declare local variables
  WSADATA wsaData;
  long lResult = 0;
  BOOL bResult = FALSE;
  SOCKET sMetNet = INVALID_SOCKET;
  struct hostent *pheMetNet = NULL;
  struct servent *pseMetNet = NULL;
  struct sockaddr_in saAddress;
  unsigned long ulCommand = 1;
  char szTelegramData[1024] = "";


  // Get actual communication socket with MetNet-Server
  //sMetNet = (SOCKET)GetTagSDWord("socketState");   // Tag Signed 16-Bit Value
sMetNet=0;
//printf("变量名称%d\n",sMetNet);


  // Examine for active connection with MetNet-Server
  if( (sMetNet == INVALID_SOCKET) || (sMetNet == 0) )
  {
// 加载socket动态链接库(dll)
    WORD wVersionRequested;
    WSADATA wsaData;    // 这结构是用于接收Wjndows Socket的结构信息的
    int err;
 
    wVersionRequested = MAKEWORD( 1, 1 );   // 请求1.1版本的WinSock库
 
    err = WSAStartup( wVersionRequested, &wsaData );
    // Create communication socket
    sMetNet = socket(AF_INET, SOCK_STREAM,0);
    // printf("port------------------->>%d\n",err );
    if( sMetNet == SOCKET_ERROR )
    {
      GetSocketError(0, "Cannot create socket");
    }
    // Prepare communication parameter with MetNet-Server
    saAddress.sin_addr.s_addr =   inet_addr(SERVER_IP);
    saAddress.sin_family = AF_INET;
    saAddress.sin_port =  htons(PORT);
    // Open communication with MetNet-Server
    lResult = connect(sMetNet, (const struct sockaddr *)&saAddress, sizeof(saAddress));


    if( lResult == SOCKET_ERROR )
    {
      GetSocketError(sMetNet, "Cannot connect to server %s", SERVER_IP);
    }
    else
    {
   lResult=send(sMetNet, "nihao\r\n", strlen("nihao\r\n")+1, 0);  // 发送显示欢迎信息
  printf("发送完毕!\n");
  lResult = recv(sMetNet, &szTelegramData[0], (sizeof(szTelegramData) - 1), 0);
  printf("接收完毕!\n");
  if( (lResult > 0) && (WSAGetLastError() == 0) )
  {
    // Terminate receive telegram data
    szTelegramData[lResult] = '\0';
    // Your code ...
   printf("服务器返回数据----------------------------------->%s\n", szTelegramData);
  }
  else
  {
   printf("----------------------------------->%d\n",  lResult );
    // Examine for socket failure (e.g. network error)
    if( (lResult == 0) && (WSAGetLastError() != WSAEWOULDBLOCK) )
    {
      // Close communication with MetNet-Server
      sMetNet = GetSocketError(sMetNet, "Cannot read data from server %s",SERVER_IP);
    }
}
    closesocket(sMetNet);
    WSACleanup();
  }
}
  // Finish action
}



server——————————————————————————————————————————————————————————————————————

#include "apdefap.h"
void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
// WINCC:TAGNAME_SECTION_START
// syntax: #define TagNameInAction "DMTagName"
// next TagID : 1
// WINCC:TAGNAME_SECTION_END


// WINCC:PICNAME_SECTION_START
// syntax: #define PicNameInAction "PictureName"
// next PicID : 1
// WINCC:PICNAME_SECTION_END




// Include header files
#include "WSOCK32.h"


#define PORT 6662
#define SERVER_IP "0.0.0.0"
SOCKET sMetNet = INVALID_SOCKET;
SOCKET ClientSocket;
                struct servent *pseMetNet = NULL;
struct sockaddr_in saAddress,ClientAddr;
int AddrLen = 0;
                int i=0;
   // Examine for active connection with MetNet-Server
   if( (sMetNet == INVALID_SOCKET) || (sMetNet == 0) )
   {
// 加载socket动态链接库(dll)
   WORD wVersionRequested;
   // 这结构是用于接收Wjndows Socket的结构信息的
   WSADATA wsaData;   
//接收执行结果,用来判断是否正确  
   int ret;
   // 请求1.1版本的WinSock库
   wVersionRequested = MAKEWORD( 1, 1 );
   //测试执行步骤 
   printf("%s\n","test");
   ret = WSAStartup( wVersionRequested, &wsaData );
   // Create communication socket
   sMetNet = socket(AF_INET, SOCK_STREAM,0);
   // printf("port------------------->>%d\n",err );
   if( sMetNet == SOCKET_ERROR )
   {
     GetSocketError(0, "Cannot create socket");
   }
                    SetTagSDWord("socketState", sMetNet);
   // Prepare communication parameter with MetNet-Server
   saAddress.sin_addr.s_addr =   inet_addr(SERVER_IP);
   saAddress.sin_family = AF_INET;
   saAddress.sin_port =  htons(PORT);
   //将套接字绑定于特定地址的特定端口,其中第二个参数可以使用SOCKADDR_IN来代替。
  ret=bind(sMetNet,(const struct sockaddr *)&saAddress,sizeof(saAddress));
  if(ret != 0)
  {
      GetSocketError(0, "Bind failed!");
  }
// 第一个参数指定需要设置的套接字,第二个参数为(等待连接队列的最大长度)
  ret= listen(sMetNet, 10);
  if(ret != 0)
  {
      GetSocketError(0, "listen failed!");
  }
   printf("Server is listening\n");

//循环等待客户端接入 
 while ( 1 )
    {
                                                                char recvchar[100];
printf("等待客户端接入,第%d个",i);
AddrLen = sizeof(ClientAddr);
ClientSocket = accept(sMetNet, (struct sockaddr*)&ClientAddr, &AddrLen);
if ( ClientSocket == INVALID_SOCKET )
{
GetSocketError(0, "Accept failed!");
break;
}
printf("client ip is: %s and the port is:%d",inet_ntoa (ClientAddr.sin_addr),ClientAddr.sin_port);
                                                                send(ClientSocket ,"nihao\r\n", strlen("nihao\r\n")+1,0);




                                                                 recv(ClientSocket ,recvchar,100,0);//本函数用于已连接的数据报或流式套接口s进行数据的接收
                                                 printf("%s\n",recvchar);
closesocket(ClientSocket );
i++;
}

}


  // Finish action


项目脚本————————————————————————————————————————————————————————————————————————

// Include header files
#include "WSOCK32.h"




unsigned int GetSocketError(unsigned int sSocket, char *lpszFormatMessage, ...)
{


  // Declare local variables
  va_list vlErrorValues;
  int iLastSocketError = 0;
  int iNewSocketError = 0;
  static char   szLastErrorMessage[254 + 1] = "";
  char          szNewErrorMessage[254 + 1] = "";


  // Get last and new socket error
  iNewSocketError = WSAGetLastError();


  // Get new error message
  if( lpszFormatMessage != NULL )
  {
    va_start(vlErrorValues, lpszFormatMessage);
    vsprintf(&szNewErrorMessage[0], lpszFormatMessage, vlErrorValues);
    va_end(vlErrorValues);
  }


  // Close open communication socket
  if( sSocket > 0 )
  {
    shutdown(sSocket, 2);
    closesocket(sSocket);
    SetTagSDWord(HMI_SA_METNETSOCKET, INVALID_SOCKET);
  }


  // Write socket error message
  printf("== SOCKET ERROR =========================================\r\n");
  printf("  Socket error\t:  %d\r\n", iNewSocketError);
  if( strlen(&szNewErrorMessage[0]) > 0 )
    printf("  Error message\t:  %s\r\n", &szNewErrorMessage[0]);
  printf("=========================================================\r\n");


  // Finish function
  return(INVALID_SOCKET);


}

全局头文件——————————————————————————————————————————————————————————————————————

//--------------------------------------------------------------------------------
// 
// Function : WSOCK32.H Winsocket definitions
//
// Reference : Definitions to be used with the WSOCK32.DLL
//
//--------------------------------------------------------------------------------


#ifndef __WSOCK32


#define __WSOCK32 1


// Basic system type definitions, taken from the BSD file sys/types.h
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
typedef int INT_PTR, *PINT_PTR;
typedef unsigned int UINT_PTR, *PUINT_PTR;
typedef long LONG_PTR, *PLONG_PTR;
typedef unsigned long ULONG_PTR, *PULONG_PTR;


// The new type to be used in all instances which refer to sockets
typedef INT_PTR SOCKET;


//
#define WSADESCRIPTION_LEN      256
#define WSASYS_STATUS_LEN       128


typedef struct WSAData 
{
  WORD                    wVersion;
  WORD                    wHighVersion;
  char                    szDescription[WSADESCRIPTION_LEN+1];
  char                    szSystemStatus[WSASYS_STATUS_LEN+1];
  unsigned short          iMaxSockets;
  unsigned short          iMaxUdpDg;
  char FAR *              lpVendorInfo;
} WSADATA;


typedef WSADATA *LPWSADATA;


// Internet address (old style... should be updated)
#ifndef s_addr


struct in_addr {
        union {
                struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
                struct { u_short s_w1,s_w2; } S_un_w;
                u_long S_addr;
        } S_un;
        #define s_addr  S_un.S_addr // can be used for most tcp & ip code
        #define s_host  S_un.S_un_b.s_b2 // host on imp
        #define s_net   S_un.S_un_b.s_b1 // network
        #define s_imp   S_un.S_un_w.s_w2 // imp
        #define s_impno S_un.S_un_b.s_b4 // imp #
        #define s_lh    S_un.S_un_b.s_b3 // logical host
};


#endif


// Socket address, internet style
struct sockaddr_in
{
short   sin_family;
u_short sin_port;
struct  in_addr sin_addr;
char    sin_zero[8];
};


// Structures returned by network data base library, taken from the
// BSD file netdb.h.  All addresses are supplied in host order, and
// returned in network order (suitable for use in system calls).
struct  hostent
{
char    FAR * h_name;           // official name of host
char    FAR * FAR * h_aliases; // alias list
short   h_addrtype; // host address type
short   h_length;               // length of address
char    FAR * FAR * h_addr_list; // list of addresses
#define h_addr  h_addr_list[0] // address, for backward compat
};


struct  servent 
{
char    FAR * s_name; // official service name
char    FAR * FAR * s_aliases; // alias list
short   s_port;                 // port #
char    FAR * s_proto;           // protocol to use
};




// Commands for ioctlsocket(),  taken from the BSD file fcntl.h.
#define IOCPARM_MASK    0x7f           // parameters must be < 128 bytes
#define IOC_VOID        0x20000000       // no parameters
#define IOC_OUT         0x40000000       // copy out parameters
#define IOC_IN          0x80000000     // copy in parameters
#define IOC_INOUT       (IOC_IN|IOC_OUT) // 0x20000000 distinguishes new & old ioctl's


#define _IO(x,y)        (IOC_VOID|((x)<<8)|(y))
#define _IOR(x,y,t)     (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
#define _IOW(x,y,t)     (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))


#define FIONREAD    _IOR('f', 127, u_long) // get # bytes to read
#define FIONBIO     _IOW('f', 126, u_long) // set/clear non-blocking i/o
#define FIOASYNC    _IOW('f', 125, u_long) // set/clear async i/o




// This is used instead of -1, since the SOCKET type is unsigned.
#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)


// Types
#define SOCK_STREAM     1               // stream socket


// Address families.
#define AF_UNSPEC       0 // unspecified
#define AF_UNIX         1   // local to host (pipes, portals)
#define AF_INET         2               // internetwork: UDP, TCP, etc.
#define AF_IMPLINK      3               // arpanet imp addresses
#define AF_PUP          4               // pup protocols: e.g. BSP
#define AF_CHAOS        5               // mit CHAOS protocols
#define AF_IPX          6               // IPX and SPX */
#define AF_NS           6               // XEROX NS protocols
#define AF_ISO          7               // ISO protocols
#define AF_OSI          AF_ISO           // OSI is ISO
#define AF_ECMA         8               // european computer manufacturers
#define AF_DATAKIT      9               // datakit protocols
#define AF_CCITT        10               // CCITT protocols, X.25 etc
#define AF_SNA          11               // IBM SNA
#define AF_DECnet       12               // DECnet
#define AF_DLI          13               // Direct data link interface
#define AF_LAT          14               // LAT
#define AF_HYLINK       15               // NSC Hyperchannel
#define AF_APPLETALK    16               // AppleTalk
#define AF_NETBIOS      17               // NetBios-style addresses
#define AF_VOICEVIEW    18               // VoiceView
#define AF_FIREFOX      19               // FireFox
#define AF_UNKNOWN1     20               // Somebody is using this!
#define AF_BAN          21               // Banyan
#define AF_MAX          22 // Max address families


// Structure used by kernel to store most addresses.
struct sockaddr
{
u_short sa_family;               // address family
char    sa_data[14];   // up to 14 bytes of direct address
};


// WinSock error codes are also defined in winerror.h
#ifndef WSABASEERR
#define WSABASEERR              10000
#define WSAEINTR                (WSABASEERR+4)
#define WSAEBADF                (WSABASEERR+9)
#define WSAEACCES               (WSABASEERR+13)
#define WSAEFAULT               (WSABASEERR+14)
#define WSAEINVAL               (WSABASEERR+22)
#define WSAEMFILE               (WSABASEERR+24)
#define WSAEWOULDBLOCK          (WSABASEERR+35)
#define WSAEINPROGRESS          (WSABASEERR+36)
#define WSAEALREADY             (WSABASEERR+37)
#define WSAENOTSOCK             (WSABASEERR+38)
#define WSAEDESTADDRREQ         (WSABASEERR+39)
#define WSAEMSGSIZE             (WSABASEERR+40)
#define WSAEPROTOTYPE           (WSABASEERR+41)
#define WSAENOPROTOOPT          (WSABASEERR+42)
#define WSAEPROTONOSUPPORT      (WSABASEERR+43)
#define WSAESOCKTNOSUPPORT      (WSABASEERR+44)
#define WSAEOPNOTSUPP           (WSABASEERR+45)
#define WSAEPFNOSUPPORT         (WSABASEERR+46)
#define WSAEAFNOSUPPORT         (WSABASEERR+47)
#define WSAEADDRINUSE           (WSABASEERR+48)
#define WSAEADDRNOTAVAIL        (WSABASEERR+49)
#define WSAENETDOWN             (WSABASEERR+50)
#define WSAENETUNREACH          (WSABASEERR+51)
#define WSAENETRESET            (WSABASEERR+52)
#define WSAECONNABORTED         (WSABASEERR+53)
#define WSAECONNRESET           (WSABASEERR+54)
#define WSAENOBUFS              (WSABASEERR+55)
#define WSAEISCONN              (WSABASEERR+56)
#define WSAENOTCONN             (WSABASEERR+57)
#define WSAESHUTDOWN            (WSABASEERR+58)
#define WSAETOOMANYREFS         (WSABASEERR+59)
#define WSAETIMEDOUT            (WSABASEERR+60)
#define WSAECONNREFUSED         (WSABASEERR+61)
#define WSAELOOP                (WSABASEERR+62)
#define WSAENAMETOOLONG         (WSABASEERR+63)
#define WSAEHOSTDOWN            (WSABASEERR+64)
#define WSAEHOSTUNREACH         (WSABASEERR+65)
#define WSAENOTEMPTY            (WSABASEERR+66)
#define WSAEPROCLIM             (WSABASEERR+67)
#define WSAEUSERS               (WSABASEERR+68)
#define WSAEDQUOT               (WSABASEERR+69)
#define WSAESTALE               (WSABASEERR+70)
#define WSAEREMOTE              (WSABASEERR+71)
#define WSASYSNOTREADY          (WSABASEERR+91)
#define WSAVERNOTSUPPORTED      (WSABASEERR+92)
#define WSANOTINITIALISED       (WSABASEERR+93)
#define WSAEDISCON              (WSABASEERR+101)
#define WSAHOST_NOT_FOUND       (WSABASEERR+1001)
#define WSATRY_AGAIN            (WSABASEERR+1002)
#define WSANO_RECOVERY          (WSABASEERR+1003)
#define WSANO_DATA              (WSABASEERR+1004)
#endif // ifdef WSABASEERR


// Winsocket function declaration from WSOCK32.DLL
#pragma code("wsock32.dll")
int WSAGetLastError(void);
int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData);
int WSACleanup(void);
struct hostent *gethostbyname(const char FAR *name);
struct servent *getservbyname(const char FAR *name, const char FAR *proto);
SOCKET socket(int af, int type, int protocol);
int connect(SOCKET s, const struct sockaddr FAR *name, int namelen);
int ioctlsocket(SOCKET s, long cmd,u_long FAR *argp);
int shutdown(SOCKET s, int how);
int closesocket(SOCKET s);
int send(SOCKET s, const char FAR *buf, int len, int flags);
int recv(SOCKET s, char FAR * buf, int len, int flags);
u_long PASCAL FAR ntohl (IN u_long netlong);
u_short PASCAL FAR ntohs (IN u_short netshort);
u_long PASCAL FAR htonl ( IN u_long hostlong);
u_short PASCAL FAR htons (IN u_short hostshort);
unsigned long PASCAL FAR inet_addr (IN const char FAR * cp);
char FAR * PASCAL FAR inet_ntoa (IN struct in_addr in);
int bind(SOCKET s, const struct sockaddr FAR *name,int namelen );
int listen(SOCKET s,int connectNum);
#pragma code()




#endif /* ifdef WSOCK32.h */

 类似资料: