#include<stdio.h>
#include<stdlib.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int gsocketfd;
int WINAPI threadReceive()
{
char bzy1[1500];
struct sockaddr_in mrcSocketAddr;
int nlen;
int myrec;
while(1)
{
memset(bzy1, 0, 1500);
memset(&mrcSocketAddr, 0, sizeof(struct sockaddr_in));
nlen = sizeof(struct sockaddr_in);
myrec=recvfrom( gsocketfd,bzy1, 1500, 0, (SOCKADDR*)&mrcSocketAddr, &nlen);
if(myrec<=0)
{
printf("接受失败\n");
//printMsg_WSAGetLastError();
return -1;
}
else
{
printf("%s\n", bzy1);
}
}
}
int main()
{
WORD myword;
WSADATA mywsadata;
int mycode=0;
int socketfd=-1;
char bzyword[128]="2021031423";
struct sockaddr_in myfirstsend;
int mbyte;
myword=0x0202;
//创建网络库
mycode=WSAStartup(myword, & mywsadata);
//创建socket
socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(socketfd<=0)
{
printf("创建失败\n");
WSACleanup();
return -1;
}
else
{
printf("创建成功\n");
}
//做第一次发送
memset(&myfirstsend,0,sizeof(struct sockaddr_in));
myfirstsend.sin_family = AF_INET;
myfirstsend.sin_port = htons(2244);//对方的端口
myfirstsend.sin_addr.s_addr = inet_addr("127.0.0.1");//对方的地址
mbyte=sendto(socketfd,bzyword, 20, 0, (SOCKADDR*)&myfirstsend, sizeof(SOCKADDR));
if(mbyte<=0)
{
printf("发送失败\n");
}
else
{
printf("发送成功\n");
printf("%d\n",mbyte);
}
CreateThread((LPSECURITY_ATTRIBUTES)NULL,
0,
(LPTHREAD_START_ROUTINE)threadReceive,
(LPVOID)NULL,
0, 0);
gsocketfd=socketfd;
while(1)
{
printf("您可以发送了\n");
system("pause");
memset(&myfirstsend,0,sizeof(struct sockaddr_in));
myfirstsend.sin_family = AF_INET;
myfirstsend.sin_port = htons(2244);//对方的端口
myfirstsend.sin_addr.s_addr = inet_addr("127.0.0.1");//对方的地址
mbyte=sendto(socketfd,bzyword, 20, 0, (SOCKADDR*)&myfirstsend, sizeof(SOCKADDR));
if(mbyte<=0)
{
printf("发送失败\n");
}
else
{
printf("发送成功\n");
printf("%d\n",mbyte);
}
}
closesocket(socketfd);
WSACleanup();
system("pause");
return 0;
}