Exemplo n.º 1
0
int main(int argc, char **argv)
{
	if(argc != 2)
	{
		cout << "Usage:\n";
		cout << "\t./server [listen port]\n";
		return -1;
	}

	if(atoi(argv[1]) < 0 || atoi(argv[1]) > 65535)
	{
		cout << "The port must be between 0 and 65535\n";
		return -1;
	}

	MyTcpSocket mySocket;
	if(!mySocket.listen(atoi(argv[1])))
		cout << "There was an error listening\n";

	char data[W*MSS];
	int n;
	
	while((n = mySocket.receive(data)) != -1)
	{
		cout << "Received data from client.\n";
		cout << "echoing " << n << " bytes to client\n";
		mySocket.send(data, n);	// Echo back to client
	}
}
Exemplo n.º 2
0
int main(int argc, char* argv[])
{
	// If the user didn't give us the correct command line args, print usage
	if(argc != 4)
	{
		cout << "Usage:\n";
		cout << "\t./client IP Port file\n";
		return -1;
	}

	// If the user entered an invalid port, tell them
	if(atoi(argv[2]) < 0 || atoi(argv[2]) > 65535)
	{
		cout << "The port must be between 0 and 65535\n";
		return -1;
	}

	FILE *receive = fopen(FILENAME, "w");	// The file to write the echoed data to
	FILE *send = fopen(argv[3], "rb");		// The file to send
	if(send == NULL)
	{
		cout << "\"" << argv[3] << "\" could not be read\n";
		return -1;
	}

	if(receive == NULL)
	{
		cout << "\"" << FILENAME << "\" could not be opened for write\n";
		return -1;
	}
	
	// Load the file to send into memory
	fseek (send, 0, SEEK_END);
	unsigned long fileLength = ftell(send);
	rewind (send);
	size_t result;
	char* buffer = new char[fileLength];
	result = fread(buffer, sizeof(buffer[0]), fileLength, send);	// copy the file into the buffer
	fclose(send);

	char recv[fileLength];
	MyTcpSocket mySocket;
	while(!mySocket.connect(argv[1], atoi(argv[2])));	// Keep trying to connect forever
	
	// Iterate over the buffer and send MSS*W at a time
	unsigned long bufsize = fileLength;
  unsigned long total = fileLength;
	unsigned long index = 0;


	while(true)
	{
		int bufSize = fileLength < MSS*W ? fileLength : MSS*W;
		
		// Copy MSS*W into a temp buffer
		char sendBuf[bufSize], recvline[MSS*W];
		for(int i = 0; i < bufSize; ++i, index++)
			sendBuf[i] = buffer[index];
			
    cout << "\t\t\t" << fileLength << "\\" << total << "\n";
		mySocket.send(sendBuf, bufSize);	// Send the chunk
	
		int n = mySocket.receive(recvline);
		fwrite(recvline, sizeof(recvline[0]), n, receive);

		if(bufSize < MSS*W)
			break;
		else
			fileLength -= MSS*W;
	}
	
	fclose(receive);

	mySocket.close();	// Close the socket	

	return 0;
}