1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <winsock2.h>
#include <fstream>
#include <string>
#pragma comment(lib,"ws2_32.lib")
#define SERVER "127.0.0.1" //ip address of udp server
#define BUFLEN 512 //Max length of buffer
#define PORT 5555 //The port on which to listen for incoming data
int main(void)
{
struct sockaddr_in si_other;
SOCKET s;
int s, slen=sizeof(si_other);
char buffer[BUFLEN];
const char * c;
std::string message;
WSADATA wsa;
std::ifstream myfile;
myfile.open ("C:\\Users\\bbbbb\\Desktop\\data.txt");
// Check whether the file failed to be open
if (myfile.fail())
{
std::cerr << "The file could not be opened. " << std::endl;
}
//Initialise winsock
std::cout << "\nInitialising Winsock..." << std::endl;
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
std::cout << "Failed. Error Code : " << WSAGetLastError() << std::endl;
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//create socket
if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
std::cout << "socket() failed. Error: " << WSAGetLastError() << std::endl;
exit(EXIT_FAILURE);
}
//setup address structure
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
//start communication
while( !myfile.eof() )
{
std::getline(myfile, message);
c = message.c_str();
//send the message
if (sendto(s, c, strlen(c) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
std::cout << "sendto() failed. Error: " << WSAGetLastError() << std::endl;
break;
}
//clear the buffer
memset(buffer,'\0', BUFLEN);
//receive Data from Server
if (recvfrom(s, buffer, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
{
std::cout << "recvfrom() failed. Error: " << WSAGetLastError() << std::endl;
break;
}
std::cout << buffer << std::endl;
}
myfile.close();
closesocket(s);
WSACleanup();
return 0;
}
|