Vxworks和windows端的socket udp通信
程序员文章站
2022-06-29 18:58:40
...
Vxworks接收端
#include <stio.h>
#include <sockLib.h>
#include <inetLib.h>
int Mainapp()
{
INT8 recvBuf[2048] = {0, };
INT8 recvBuf[2048] = {0, };
INT32 retCode = 0;
UINT32 rxSocket = 0;
//两个地址结构体
struct sockaddr_in rxAddr;
struct sockaddr_in txAddr;
UINT32 port = 50000;
INT32 rxAddrSize = 0;
INT32 txAddrSize = 0;
INT32 rxLen = 0;
INT32 txLen = 0;
//创建套接字,UDP
rxSocket = socket(AF_INET, SOCK_DGRAE, IPPROTO_UDP);
//地址赋值
txAddrSize = sizeof(txAddr);
rxAddrSize = sizeof(rxAddr);
rxAddr.sin_family = AF_INET;
rxAddr.sin_port = htons(port);
rxAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定套接字
retCode = bind(rxSocket, (struct sockaddr *)&rxAddr, rxAddrSize);
if(ERROR == retCode)
{
printf("tSocketCfg bind error\n!");
return;
}
//不断接受消息
while(1)
{
//清理recvbuf
memset(recvbuf,0,sizeof(recvBuf));
//接受数据
rxLen = recvfrom(rxSocket, (char*)&recvBuf[0], sizeof(recvBuf),0,(struct sockaddr*)&txAddr, &txAddrSize);
if(ERROR == rxLen)
{
printf("tSocketCfg recvfrom error\n");
continue;
}
printf("Recv :%s\n",recvBuf);
sprintf(sendBuf, "I recved %s\n", recvBuf);
//回传
txLen = sendto(rxSocket, (char*)&sendBuf[0], 200, 0, (struct sockaddr*)&txAddr,txAddrSize);
if(ERROR == txLen)
{
printf("tSocketCfg send fail!");
}
}
return 0;
}
windows发送端
#include <stdio.h>
#include "winsock2.h"
#pragma comment(lib, "Ws2_32.lib");
int main()
{
int ret = 0;
SOCKET hSocket;
WSADATA wsaData;
char sendBuf[2048] = "hello world!";
char recvBuf[2048] = {0, };
struct sockaddr_in destAddr;
struct sockaddr_in srcAddr;
int AddrSize = sizeof(srcAddr);
WSAStartup(MAKEWORD(2,2), &wsaData);
hSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(50000);
destAddr.sin_addr.s_addr = inet_addr("10.5.235.245");
while(1)
{
ret = sendto(hSocket, sendBuf ,1000, 0, (struct sockaddr *)&destAddr, sizeof(destAddr));
if (ret == SOCKET_ERROR)
{
return (-1);
}
ret = recvfrom(hSockket, recvBuf, 2048, 0, (struct sockaddr *)&srcAddr, &AddrSize);
if (SOCKET+ERROR == ret)
{
printf("recvfrom error!\n");
return(-3);
}
printf("recv ip:%s, port:%d, %s\n", inet_ntoa(srcAddr.sin_Addr), ntohs(srcAddr.sin_port),recvBuf);
Sleep(1000);
}
}
推荐阅读
-
详解Android 基于TCP和UDP协议的Socket通信
-
C#基于Socket的UDP和TCP处理通信报文开发传输
-
利用windows的SOCKET编写自己的UDP通信类
-
Vxworks和windows端的socket udp通信
-
Windows下C语言的Socket编程例子(TCP和UDP)
-
Windows下C语言的Socket编程例子(TCP和UDP)
-
Day.55————C++ socket编程实现简单的UDP、TCP通信(服务端+客户端)
-
Windows环境下TCP通信的服务端和客户端
-
网络编程(InetAddress类、Socket和ServerSocket、实现客户端和服务器之间的双向通信)
-
Socket TCP 协议实现服务端和客户端的简单通信