Click here to Skip to main content
15,311,717 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
#if defined (_MSC_VER)
#include <winsock.h>
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <iostream>
#include <stdint.h>
#include <vector>

const unsigned short server_port = 5000;  // server port
void client_echo_text(const char *server_ip);
void client_send_data(const char *server_ip, const uint32_t arr_size_mult);

///////////////////////////////////////////////////////////////////////////////////////
//main
///////////////////////////////////////////////////////////////////////////////////////

// usage: 
// send N sequences 1 time to server at <IP adress>
// ./client -i <IP adress> -n N -d 
// same with infinite loop
// ./client -i <IP adress> -n N -l 

int main(int argc, char *argv[])
{
  char server_ip[255]; // server IP address (dotted quad)
  strcpy(server_ip, "127.0.0.1");
  uint32_t arr_size_mult = 10;

  //no arguments
  if (argc == 1)
  {
    client_send_data(server_ip, arr_size_mult);
  }

  for (int i = 1; i < argc && argv[i][0] == '-'; i++)
  {
    switch (argv[i][1])
    {
    case 'i':
      strcpy(server_ip, argv[i + 1]);
      i++;
      break;
    case 'e':
      client_echo_text(server_ip);
      exit(0);
      break;
    case 'n':
      arr_size_mult = atoi(argv[i + 1]);
      i++;
      break;
    case 'd':
      client_send_data(server_ip, arr_size_mult);
      exit(0);
      break;
    case 'l':
      while (true)
      {
        client_send_data(server_ip, arr_size_mult);
      }
      break;
    }
  }

  return 0;
}

///////////////////////////////////////////////////////////////////////////////////////
//client_send_data
///////////////////////////////////////////////////////////////////////////////////////

void client_send_data(const char *server_ip, const uint32_t arr_size_mult)
{
  int sock;                          // socket descriptor
  struct sockaddr_in server_addr;    // server address

  //data
  const uint32_t arr_size = arr_size_mult * 255; // array size

  //construct array
  std::vector<uint8_t> val8(arr_size);
  uint8_t v8 = 0;
  for (size_t i = 0; i < arr_size; ++i)
  {
    val8[i] = v8;
    v8++;
    if (v8 == 255)
    {
      v8 = 0;
    }
  }

#if defined (_MSC_VER)
  WSADATA ws_data;
  if (WSAStartup(MAKEWORD(2, 0), &ws_data) != 0)
  {
    exit(1);
  }
#endif

  // create a stream socket using TCP
  if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  {
    exit(1);
  }

  // construct the server address structure
  memset(&server_addr, 0, sizeof(server_addr));          // zero out structure
  server_addr.sin_family = AF_INET;                      // internet address family
  server_addr.sin_addr.s_addr = inet_addr(server_ip);    // server IP address
  server_addr.sin_port = htons(server_port);             // server port

  // establish the connection to the server
  if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
  {
    std::cout << "connect error: " << strerror(errno) << std::endl;
    exit(1);
  }

  //send array size
  if (send(sock, (char *)&arr_size, sizeof(uint32_t), 0) != sizeof(uint32_t))
  {
    exit(1);
  }

  std::cout << "client sent array size: " << (int)arr_size << std::endl;

  //send array
  for (size_t i = 0; i < arr_size; ++i)
  {
    v8 = val8[i];
    if (send(sock, (char *)&v8, sizeof(uint8_t), 0) != sizeof(uint8_t))
    {
      exit(1);
    }
  }

  std::cout << "client sent array: " << std::endl;

#if defined (_MSC_VER)
  closesocket(sock);
  WSACleanup();
#else
  close(sock);
#endif

}</pre





<pre>#if defined(_MSC_VER)
#include <winsock.h>
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <iostream>
#include <stdint.h>
#include <assert.h>
#include <vector>

const unsigned short server_port = 5000;  // server port
void server_echo_text();
void server_recv_data(bool verbose);
void check_file(const uint32_t arr_size, bool verbose, const size_t slab_size);

///////////////////////////////////////////////////////////////////////////////////////
//main
///////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char *argv[])
{
	bool verbose = false;

	//no arguments
	if (argc == 1)
	{
		server_recv_data(verbose);
	}

	for (int i = 1; i < argc && argv[i][0] == '-'; i++)
	{
		switch (argv[i][1])
		{
		case 'v':
			std::cout << "verbose mode: " << std::endl;
			verbose = true;
			break;
		case 'e':
			std::cout << "running echo server: " << std::endl;
			server_echo_text();
			exit(0);
			break;
		case 'd':
			std::cout << "running data server: " << std::endl;
			server_recv_data(verbose);
			exit(0);
			break;
		}
	}

	return 0;

}

///////////////////////////////////////////////////////////////////////////////////////
//server_recv_data
///////////////////////////////////////////////////////////////////////////////////////

void server_recv_data(bool verbose)
{
	const int MAXPENDING = 5;             // maximum outstanding connection requests
	int server_socket;                    // socket descriptor for server
	int client_socket;                    // socket descriptor for client
	sockaddr_in server_addr;              // local address
	sockaddr_in client_addr;              // client address
	int  recv_size;                       // size in bytes returned by recv() 
#if defined (_MSC_VER)
	int len_addr;                         // length of client address data structure
#else
	socklen_t len_addr;
#endif

	//data
	uint32_t arr_size = 0;
	size_t slab_size = 1;
	FILE *file;

#if defined (_MSC_VER)
	WSADATA ws_data;
	if (WSAStartup(MAKEWORD(2, 0), &ws_data) != 0)
	{
		exit(1);
	}
#endif

	// create socket for incoming connections
	if ((server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
	{
		exit(1);
	}

	// construct local address structure
	memset(&server_addr, 0, sizeof(server_addr));     // zero out structure
	server_addr.sin_family = AF_INET;                 // internet address family
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);  // any incoming interface
	server_addr.sin_port = htons(server_port);        // local port

	// bind to the local address
	if (bind(server_socket, (sockaddr*)&server_addr, sizeof(server_addr)) < 0)
	{
		//bind error: Permission denied
		//You're probably trying to bind a port under 1024. These ports usually require root privileges to be bound.
		std::cout << "bind error: " << strerror(errno) << std::endl;
		exit(1);
	}

	// mark the socket so it will listen for incoming connections
	if (listen(server_socket, MAXPENDING) < 0)
	{
		exit(1);
	}

	for (;;) // run forever
	{
		// set length of client address structure (in-out parameter)
		len_addr = sizeof(client_addr);

		// wait for a client to connect
		if ((client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &len_addr)) < 0)
		{
			exit(1);
		}

		// convert IP addresses from a dots-and-number string to a struct in_addr and back
		char *str_ip = inet_ntoa(client_addr.sin_addr);
		std::cout << "handling client " << str_ip << std::endl;

		// receive array size
		if ((recv_size = recv(client_socket, (char *)&arr_size, sizeof(uint32_t), 0)) != sizeof(uint32_t))
		{
			exit(1);
		}

		std::cout << "server received array size: " << (int)arr_size << std::endl;

		//save file
		file = fopen("file.bin", "wb");
		fwrite(&arr_size, sizeof(uint32_t), 1, file);

		//receive array
		for (size_t i = 0; i < arr_size; ++i)
		{
			uint8_t v8;
			if ((recv_size = recv(client_socket, (char *)&v8, sizeof(uint8_t), 0)) != sizeof(uint8_t))
			{
				exit(1);
			}

			//write 1 element
			fwrite(&v8, sizeof(uint8_t), slab_size, file);
		}

		fclose(file);

		std::cout << "server received array: " << std::endl;
		check_file(arr_size, verbose, slab_size);

		// close client socket
#if defined (_MSC_VER)
		closesocket(client_socket);
#else
		close(client_socket);
#endif
	}


}

///////////////////////////////////////////////////////////////////////////////////////
//check_file
///////////////////////////////////////////////////////////////////////////////////////

void check_file(const uint32_t arr_size, bool verbose, const size_t slab_size)
{
	//read file
	std::vector<uint8_t> val8(arr_size);
	std::vector<uint8_t> val8_c(arr_size);
	uint32_t arr_size_r;
	uint8_t v8;
	FILE *file;

	file = fopen("file.bin", "rb");
	fread(&arr_size_r, sizeof(uint32_t), 1, file);
	assert(arr_size_r == arr_size);

	for (size_t i = 0; i < arr_size; ++i)
	{
		fread(&v8, sizeof(uint8_t), slab_size, file);
		val8[i] = v8;
		if (verbose) std::cout << (int)val8[i] << " ";

	}
	if (verbose) std::cout << std::endl;

	fclose(file);

	//check data, define array the same as in client, compare arrays
	v8 = 0;
	for (size_t i = 0; i < arr_size; ++i)
	{
		val8_c[i] = v8;
		v8++;
		if (v8 == 255)
		{
			v8 = 0;
		}
	}

	//compare arrays
	for (size_t i = 0; i < arr_size; ++i)
	{
		if (val8_c[i] != val8[i])
		{
			std::cout << "arrays differ at: " << i << " " << (int)val8_c[i] << " " << (int)val8[i] << std::endl;
			assert(0);
		}
	}

	std::cout << "arrays match: " << (int)arr_size << " " << (int)arr_size_r << std::endl;
	std::cout << std::endl;

}


What I have tried:

I need correct Coding for UDP server and client using array
Posted
Updated 6-Jan-22 21:21pm
Comments
Richard MacCutchan 7-Jan-22 4:12am
   
"I need correct Coding for UDP server and client using array"
What does that mean? Google will find many examples of client/server using UDP. And using arrays to hold information is perfectly straightforward in C++.

1 solution

Quote:
I need correct Coding for UDP server and client using array

Unfortunately, we are not a "code to order" site.

While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900