发送端:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"WS2_32")
#define PORT 8050
void main()
{
WSADATA wsadata = { 0 };
int iResult = WSAStartup(0x0202, &wsadata);
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in sa = { AF_INET, htons(PORT) };
int n = bind(sock, (sockaddr*)&sa, sizeof(sa));
sa.sin_port = htons(18637);
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
while (true)
{
char s[100];
cin >> s;
sendto(sock, s, 3, 0, (sockaddr*)&sa, sizeof(sa));
}
//system("pause");
}
接收端:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"WS2_32")
#define PORT 18637
void main()
{
WSADATA wsadata = { 0 };
int iResult = WSAStartup(0x0202, &wsadata);
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in sa = { AF_INET, htons(PORT) };
int n = bind(sock, (sockaddr*)&sa, sizeof(sa));
while (true)
{
char s[2048];
n = recv(sock, s, sizeof(s), 0);
s[n] = '\0';
cout << s << endl;
}
//system("pause");
}
注:在同服务器通讯时需要查看防火墙是否关闭