xref: /haiku/src/servers/app/drawing/interface/remote/NetSender.cpp (revision 44d19f4d32b8f7e9c01f00294c87ca5cc2e057f7)
1 /*
2  * Copyright 2009, Haiku, Inc.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Michael Lotz <mmlr@mlotz.ch>
7  */
8 
9 #include "NetSender.h"
10 
11 #include "StreamingRingBuffer.h"
12 
13 #include <NetEndpoint.h>
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #define TRACE(x...)			/*debug_printf("NetSender: " x)*/
20 #define TRACE_ERROR(x...)	debug_printf("NetSender: " x)
21 
22 
23 NetSender::NetSender(BNetEndpoint *endpoint, StreamingRingBuffer *source)
24 	:
25 	fEndpoint(endpoint),
26 	fSource(source),
27 	fSenderThread(-1),
28 	fStopThread(false)
29 {
30 	fSenderThread = spawn_thread(_NetworkSenderEntry, "network sender",
31 		B_NORMAL_PRIORITY, this);
32 	resume_thread(fSenderThread);
33 }
34 
35 
36 NetSender::~NetSender()
37 {
38 	fStopThread = true;
39 	int32 result;
40 	wait_for_thread(fSenderThread, &result);
41 }
42 
43 
44 int32
45 NetSender::_NetworkSenderEntry(void *data)
46 {
47 	return ((NetSender *)data)->_NetworkSender();
48 }
49 
50 
51 status_t
52 NetSender::_NetworkSender()
53 {
54 	while (!fStopThread) {
55 		uint8 buffer[4096];
56 		int32 readSize = fSource->Read(buffer, sizeof(buffer), true);
57 		if (readSize < 0) {
58 			TRACE_ERROR("read failed, stopping sender thread: %s\n",
59 				strerror(readSize));
60 			return readSize;
61 		}
62 
63 		while (readSize > 0) {
64 			int32 sendSize = fEndpoint->Send(buffer, readSize);
65 			if (sendSize < 0) {
66 				TRACE_ERROR("sending data failed: %s\n", strerror(sendSize));
67 				return sendSize;
68 			}
69 
70 			readSize -= sendSize;
71 		}
72 	}
73 
74 	return B_OK;
75 }
76