]> git.saurik.com Git - wxWidgets.git/blame - samples/sockets/baseserver.cpp
Don't use printf() with non-literal string as format.
[wxWidgets.git] / samples / sockets / baseserver.cpp
CommitLineData
2804f77d
VZ
1/////////////////////////////////////////////////////////////////////////////
2// Name: samples/sockbase/client.cpp
3// Purpose: Sockets sample for wxBase
4// Author: Lukasz Michalski
5// Modified by:
6// Created: 27.06.2005
7// RCS-ID: $Id$
8// Copyright: (c) 2005 Lukasz Michalski <lmichalski@user.sourceforge.net>
526954c5 9// Licence: wxWindows licence
2804f77d
VZ
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#include "wx/wx.h"
21#include "wx/socket.h"
22#include "wx/event.h"
23#include "wx/list.h"
24#include "wx/cmdline.h"
25#include "wx/datetime.h"
26#include "wx/timer.h"
27#include "wx/thread.h"
28
e2bcc781 29const char *GetSocketErrorMsg(int pSockError)
2804f77d
VZ
30{
31 switch(pSockError)
32 {
33 case wxSOCKET_NOERROR:
e2bcc781
VZ
34 return "wxSOCKET_NOERROR";
35
2804f77d 36 case wxSOCKET_INVOP:
e2bcc781
VZ
37 return "wxSOCKET_INVOP";
38
2804f77d 39 case wxSOCKET_IOERR:
e2bcc781
VZ
40 return "wxSOCKET_IOERR";
41
2804f77d 42 case wxSOCKET_INVADDR:
e2bcc781
VZ
43 return "wxSOCKET_INVADDR";
44
2804f77d 45 case wxSOCKET_NOHOST:
e2bcc781
VZ
46 return "wxSOCKET_NOHOST";
47
2804f77d 48 case wxSOCKET_INVPORT:
e2bcc781
VZ
49 return "wxSOCKET_INVPORT";
50
2804f77d 51 case wxSOCKET_WOULDBLOCK:
e2bcc781
VZ
52 return "wxSOCKET_WOULDBLOCK";
53
2804f77d 54 case wxSOCKET_TIMEDOUT:
e2bcc781
VZ
55 return "wxSOCKET_TIMEDOUT";
56
2804f77d 57 case wxSOCKET_MEMERR:
e2bcc781
VZ
58 return "wxSOCKET_MEMERR";
59
2804f77d 60 default:
e2bcc781 61 return "Unknown";
2804f77d
VZ
62 }
63}
64
2804f77d
VZ
65//event sent by workers to server class
66//after client is served
67const wxEventType wxEVT_WORKER = wxNewEventType();
68#define EVT_WORKER(func) DECLARE_EVENT_TABLE_ENTRY( wxEVT_WORKER, -1, -1, (wxObjectEventFunction) (wxEventFunction) (WorkerEventFunction) & func, (wxObject *) NULL ),
69
e2bcc781
VZ
70class WorkerEvent : public wxEvent
71{
2804f77d
VZ
72public:
73 WorkerEvent(void* pSender)
74 {
75 SetId(-1);
76 SetEventType(wxEVT_WORKER);
77 m_sender = pSender;
78 m_exit = false;
79 m_workerFailed = false;
80 }
81
82 virtual wxEvent* Clone() const
83 {
84 return new WorkerEvent(*this);
85 }
86
87 void* m_sender;
88 bool m_exit;
89 bool m_workerFailed;
90};
91
92typedef void (wxEvtHandler::*WorkerEventFunction)(WorkerEvent&);
93
94class ThreadWorker;
95class EventWorker;
96
97WX_DECLARE_LIST(ThreadWorker, TList);
98WX_DECLARE_LIST(EventWorker, EList);
99
100//main server class contains listening socket
101//and list of two type worker classes that serve clients
102class Server : public wxApp
103{
66034aba 104 DECLARE_EVENT_TABLE()
2804f77d
VZ
105public:
106 Server() : m_maxConnections(-1) {}
107 ~Server() {}
108private:
109 enum WorkMode
110 {
111 MIXED,
112 THREADS,
113 EVENTS
114 };
115
116 virtual bool OnInit();
117 virtual int OnExit();
118
119 void OnInitCmdLine(wxCmdLineParser& pParser);
120 bool OnCmdLineParsed(wxCmdLineParser& pParser);
121
122 void OnSocketEvent(wxSocketEvent& pEvent);
123 void OnWorkerEvent(WorkerEvent& pEvent);
124 void OnTimerEvent(wxTimerEvent& pEvent);
125 void DumpStatistics();
126
127 TList m_threadWorkers;
128 EList m_eventWorkers;
129 WorkMode m_workMode;
130 wxSocketServer* m_listeningSocket;
131
132 // statistics
133 unsigned m_threadWorkersCreated;
134 unsigned m_threadWorkersDone;
135 unsigned m_threadWorkersFailed;
136 unsigned m_maxThreadWorkers;
137
138 unsigned m_eventWorkersCreated;
139 unsigned m_eventWorkersDone;
140 unsigned m_eventWorkersFailed;
141 unsigned m_maxEventWorkers;
142
143 long int m_maxConnections;
144
145 long m_port;
146
147 wxTimer mTimer;
148};
149
150DECLARE_APP(Server);
151
c3bcb48f
VZ
152// just some common things shared between ThreadWorker and EventWorker
153class WorkerBase
154{
155protected:
156 // outputs log message with IP and TCP port number prepended
157 void LogWorker(const wxString& msg, wxLogLevel level = wxLOG_Info)
158 {
159 wxLogGeneric(level,
160 "%s:%d %s", m_peer.IPAddress(), m_peer.Service(), msg);
161 }
162
163 wxIPV4address m_peer;
164};
165
2804f77d
VZ
166//thread based worker reads signature and all data first from connected client
167//and resends data to client after reading
c3bcb48f 168class ThreadWorker : public wxThread, private WorkerBase
2804f77d
VZ
169{
170public:
171 ThreadWorker(wxSocketBase* pSocket);
172 virtual ExitCode Entry();
c3bcb48f 173
2804f77d
VZ
174private:
175 wxSocketBase* m_socket;
2804f77d
VZ
176};
177
178//event based worker reads signature and creates buffer for incoming data.
179//When part of data arrives this worker resends it as soon as possible.
c3bcb48f 180class EventWorker : public wxEvtHandler, private WorkerBase
2804f77d 181{
2804f77d
VZ
182public:
183 EventWorker(wxSocketBase* pSock);
c3bcb48f
VZ
184 virtual ~EventWorker();
185
2804f77d
VZ
186private:
187 wxSocketBase* m_socket;
2804f77d
VZ
188
189 unsigned char m_signature[2];
190 char* m_inbuf;
191 int m_infill;
192 int m_size;
193 char* m_outbuf;
194 int m_outfill;
195 int m_written;
196
197 void OnSocketEvent(wxSocketEvent& pEvent);
198 void DoWrite();
199 void DoRead();
c3bcb48f 200
66034aba 201 DECLARE_EVENT_TABLE()
2804f77d
VZ
202};
203
204/******************* Implementation ******************/
205IMPLEMENT_APP_CONSOLE(Server)
206
207#include <wx/listimpl.cpp>
208WX_DEFINE_LIST(TList);
209WX_DEFINE_LIST(EList);
210
211
212void
213Server::OnInitCmdLine(wxCmdLineParser& pParser)
214{
215 wxApp::OnInitCmdLine(pParser);
c3bcb48f
VZ
216 pParser.AddSwitch("t","threads","Use thread based workers only");
217 pParser.AddSwitch("e","events","Use event based workers only");
218 pParser.AddOption("m","max","Exit after <n> connections",
219 wxCMD_LINE_VAL_NUMBER);
220 pParser.AddOption("p","port","listen on given port (default 3000)",
221 wxCMD_LINE_VAL_NUMBER);
2804f77d
VZ
222}
223
224void
225Server::DumpStatistics()
226{
227 wxString mode;
228 switch(m_workMode)
229 {
230 case EVENTS:
c3bcb48f 231 mode = "Event based workers";
2804f77d
VZ
232 break;
233 case THREADS:
c3bcb48f 234 mode = "Thread based workers";
2804f77d
VZ
235 break;
236 case MIXED:
c3bcb48f 237 mode = "Event and thread based workers";
2804f77d
VZ
238 break;
239 }
e2bcc781
VZ
240 wxLogMessage("Server mode: %s",mode);
241 wxLogMessage("\t\t\t\tThreads\tEvents\tTotal");
242 wxLogMessage("Workers created:\t\t%d\t%d\t%d",
243 m_threadWorkersCreated,
244 m_eventWorkersCreated,
245 m_threadWorkersCreated + m_eventWorkersCreated);
246 wxLogMessage("Max concurrent workers:\t%d\t%d\t%d",
247 m_maxThreadWorkers,
248 m_maxEventWorkers,
249 m_maxThreadWorkers + m_maxEventWorkers);
250 wxLogMessage("Workers failed:\t\t%d\t%d\t%d",
251 m_threadWorkersFailed,
252 m_eventWorkersFailed,
253 m_threadWorkersFailed + m_eventWorkersFailed);
254 wxLogMessage("Workers done:\t\t%d\t%d\t%d",
255 m_threadWorkersDone,
256 m_eventWorkersDone,
257 m_threadWorkersDone + m_eventWorkersDone);
2804f77d
VZ
258
259 if ((int)(m_threadWorkersDone+m_eventWorkersDone) == m_maxConnections)
260 {
e2bcc781 261 wxLogMessage("%d connection(s) served, exiting",m_maxConnections);
2804f77d
VZ
262 ExitMainLoop();
263 }
264}
265
266
267bool
268Server::OnCmdLineParsed(wxCmdLineParser& pParser)
269{
c3bcb48f 270 if (pParser.Found("verbose"))
2804f77d 271 {
e2bcc781
VZ
272 wxLog::AddTraceMask("wxSocket");
273 wxLog::AddTraceMask("epolldispatcher");
274 wxLog::AddTraceMask("selectdispatcher");
275 wxLog::AddTraceMask("thread");
276 wxLog::AddTraceMask("events");
277 wxLog::AddTraceMask("timer");
2804f77d
VZ
278 }
279
e2bcc781 280 if (pParser.Found("m",&m_maxConnections))
2804f77d 281 {
e2bcc781 282 wxLogMessage("%d connection(s) to exit",m_maxConnections);
2804f77d
VZ
283 }
284
e2bcc781 285 if (pParser.Found("p",&m_port))
2804f77d 286 {
e2bcc781 287 wxLogMessage("%d connection(s) to exit",m_maxConnections);
2804f77d
VZ
288 }
289
e2bcc781 290 if (pParser.Found("t"))
2804f77d 291 m_workMode = THREADS;
e2bcc781 292 else if (pParser.Found("e"))
2804f77d
VZ
293 m_workMode = EVENTS;
294 else
295 m_workMode = MIXED;
296
297 return wxApp::OnCmdLineParsed(pParser);
298}
299
300bool Server::OnInit()
301{
302 wxLog* logger = new wxLogStderr();
303 wxLog::SetActiveTarget(logger);
304
305 m_port = 3000;
306
307 //send interesting things to console
308 if (!wxApp::OnInit())
309 return false;
310
311 //setup listening socket
312 wxIPV4address la;
313 la.Service(m_port);
314 m_listeningSocket = new wxSocketServer(la,wxSOCKET_NOWAIT|wxSOCKET_REUSEADDR);
315 m_listeningSocket->SetEventHandler(*this);
316 m_listeningSocket->SetNotify(wxSOCKET_CONNECTION_FLAG);
317 m_listeningSocket->Notify(true);
a1b806b9 318 if (!m_listeningSocket->IsOk())
2804f77d 319 {
e2bcc781 320 wxLogError("Cannot bind listening socket");
2804f77d
VZ
321 return false;
322 }
323
324 m_threadWorkersCreated = 0;
325 m_threadWorkersDone = 0;
326 m_threadWorkersFailed = 0;
327 m_maxThreadWorkers = 0;
328
329 m_eventWorkersCreated = 0;
330 m_eventWorkersDone = 0;
331 m_eventWorkersFailed = 0;
332 m_maxEventWorkers = 0;
333
e2bcc781 334 wxLogMessage("Server listening at port %d, waiting for connections", m_port);
2804f77d
VZ
335 return true;
336}
337
338
339int Server::OnExit()
340{
e2bcc781
VZ
341 for ( TList::compatibility_iterator it = m_threadWorkers.GetFirst();
342 it;
343 it = it->GetNext() )
344 {
2804f77d
VZ
345 it->GetData()->Wait();
346 delete it->GetData();
347 }
348
e2bcc781
VZ
349 for ( EList::compatibility_iterator it2 = m_eventWorkers.GetFirst();
350 it2;
351 it2->GetNext() )
352 {
45a50a2e 353 delete it2->GetData();
2804f77d
VZ
354 }
355
356 m_threadWorkers.Clear();
357 m_eventWorkers.Clear();
358 m_listeningSocket->Destroy();
359 return 0;
360}
361
362void Server::OnSocketEvent(wxSocketEvent& pEvent)
363{
364 switch(pEvent.GetSocketEvent())
365 {
366 case wxSOCKET_INPUT:
e2bcc781
VZ
367 wxLogError("Unexpected wxSOCKET_INPUT in wxSocketServer");
368 break;
2804f77d 369 case wxSOCKET_OUTPUT:
e2bcc781 370 wxLogError("Unexpected wxSOCKET_OUTPUT in wxSocketServer");
2804f77d
VZ
371 break;
372 case wxSOCKET_CONNECTION:
373 {
374 wxSocketBase* sock = m_listeningSocket->Accept();
375 wxIPV4address addr;
376 if (!sock->GetPeer(addr))
377 {
e2bcc781 378 wxLogError("Server: cannot get peer info");
2804f77d 379 } else {
e2bcc781 380 wxLogMessage("Got connection from %s:%d",addr.IPAddress().c_str(), addr.Service());
2804f77d
VZ
381 }
382 bool createThread;
383
384 if (m_workMode != MIXED)
385 createThread = m_workMode == THREADS;
386 else
387 createThread = (wxDateTime::Now().GetSecond())%2 == 0;
388
389 if (createThread)
390 {
391 ThreadWorker* c = new ThreadWorker(sock);
392 if (c->Create() == wxTHREAD_NO_ERROR)
393 {
394 m_threadWorkers.Append(c);
395 if (m_threadWorkers.GetCount() > m_maxThreadWorkers)
396 m_maxThreadWorkers++;
397 m_threadWorkersCreated++;
398 c->Run();
399 }
400 else
401 {
e2bcc781 402 wxLogError("Server: cannot create next thread (current threads: %d", m_threadWorkers.size());
2804f77d
VZ
403 };
404 }
405 else
406 {
407 EventWorker* w = new EventWorker(sock);
408 m_eventWorkers.Append(w);
409 if (m_eventWorkers.GetCount() > m_maxEventWorkers)
410 m_maxEventWorkers++;
411 m_eventWorkersCreated++;
412 }
413 }
414 break;
415 case wxSOCKET_LOST:
e2bcc781 416 wxLogError("Unexpected wxSOCKET_LOST in wxSocketServer");
2804f77d
VZ
417 break;
418 }
419}
420
421void Server::OnWorkerEvent(WorkerEvent& pEvent)
422{
e2bcc781 423 //wxLogMessage("Got worker event");
2804f77d
VZ
424 for(TList::compatibility_iterator it = m_threadWorkers.GetFirst(); it ; it = it->GetNext())
425 {
426 if (it->GetData() == pEvent.m_sender)
427 {
e2bcc781
VZ
428 wxLogVerbose("Deleting thread worker (%d left)",
429 m_threadWorkers.GetCount());
2804f77d
VZ
430 it->GetData()->Wait();
431 delete it->GetData();
432 m_threadWorkers.DeleteNode(it);
433 if (!pEvent.m_workerFailed)
434 m_threadWorkersDone++;
435 else
436 m_threadWorkersFailed++;
437 break;
438 }
439 }
45a50a2e 440 for(EList::compatibility_iterator it2 = m_eventWorkers.GetFirst(); it2 ; it2 = it2->GetNext())
2804f77d 441 {
45a50a2e 442 if (it2->GetData() == pEvent.m_sender)
2804f77d 443 {
e2bcc781
VZ
444 wxLogVerbose("Deleting event worker (%d left)",
445 m_eventWorkers.GetCount());
45a50a2e
VZ
446 delete it2->GetData();
447 m_eventWorkers.DeleteNode(it2);
2804f77d
VZ
448 if (!pEvent.m_workerFailed)
449 m_eventWorkersDone++;
450 else
451 m_eventWorkersFailed++;
452 break;
453 }
454 }
455
456 if (m_eventWorkers.GetCount() == 0 && m_threadWorkers.GetCount() == 0)
457 {
458 mTimer.Start(1000,true);
459 }
460}
461
462void Server::OnTimerEvent(wxTimerEvent&)
463{
464 DumpStatistics();
465}
466
467
468BEGIN_EVENT_TABLE(Server,wxEvtHandler)
469 EVT_SOCKET(wxID_ANY,Server::OnSocketEvent)
470 EVT_WORKER(Server::OnWorkerEvent)
471 EVT_TIMER(wxID_ANY,Server::OnTimerEvent)
472END_EVENT_TABLE()
473
474
475ThreadWorker::ThreadWorker(wxSocketBase* pSocket) : wxThread(wxTHREAD_JOINABLE)
476{
477 m_socket = pSocket;
478 //Notify() cannot be called in thread context. We have to detach from main loop
479 //before switching thread contexts.
480 m_socket->Notify(false);
481 m_socket->SetFlags(wxSOCKET_WAITALL|wxSOCKET_BLOCK);
482 pSocket->GetPeer(m_peer);
483}
484
485wxThread::ExitCode ThreadWorker::Entry()
486{
487 WorkerEvent e(this);
488 if (!m_socket->IsConnected())
489 {
c3bcb48f 490 LogWorker("ThreadWorker: not connected",wxLOG_Error);
2804f77d
VZ
491 return 0;
492 }
493 int to_process = -1;
494 if (m_socket->IsConnected())
495 {
496 unsigned char signature[2];
c3bcb48f 497 LogWorker("ThreadWorker: reading for data");
2804f77d
VZ
498 to_process = 2;
499 do
500 {
501 m_socket->Read(&signature,to_process);
502 if (m_socket->Error())
503 {
c3bcb48f 504 LogWorker("ThreadWorker: Read error",wxLOG_Error);
2804f77d
VZ
505 wxGetApp().AddPendingEvent(e);
506 return 0;
507 }
508 to_process -= m_socket->LastCount();
c3bcb48f 509 LogWorker(wxString::Format("to_process: %d",to_process));
2804f77d
VZ
510
511 }
512 while (!m_socket->Error() && to_process != 0);
513
514 if (signature[0] == 0)
515 {
516 e.m_exit = true;
517 return 0;
518 }
519
520 if (signature[0] == 0xCE)
521 {
c3bcb48f 522 LogWorker("This server does not support test2 from GUI client",wxLOG_Error);
2804f77d
VZ
523 e.m_workerFailed = true;
524 e.m_exit = true;
525 return 0;
526 }
527 int size = signature[1] * (signature[0] == 0xBE ? 1 : 1024);
528 char* buf = new char[size];
c3bcb48f 529 LogWorker(wxString::Format("Message signature: chunks: %d, kilobytes: %d, size: %d (bytes)",signature[0],signature[1],size));
2804f77d
VZ
530
531 to_process = size;
c3bcb48f 532 LogWorker(wxString::Format("ThreadWorker: reading %d bytes of data",to_process));
2804f77d
VZ
533
534 do
535 {
536 m_socket->Read(buf,to_process);
537 if (m_socket->Error())
538 {
c3bcb48f 539 LogWorker("ThreadWorker: Read error",wxLOG_Error);
2804f77d
VZ
540 wxGetApp().AddPendingEvent(e);
541 return 0;
542 }
543 to_process -= m_socket->LastCount();
c3bcb48f 544 LogWorker(wxString::Format("ThreadWorker: %d bytes readed, %d todo",m_socket->LastCount(),to_process));
2804f77d
VZ
545
546 }
547 while(!m_socket->Error() && to_process != 0);
548
549 to_process = size;
550
551 do
552 {
553 m_socket->Write(buf,to_process);
e2bcc781
VZ
554 if (m_socket->Error())
555 {
c3bcb48f 556 LogWorker("ThreadWorker: Write error",wxLOG_Error);
2804f77d 557 break;
e2bcc781 558 }
2804f77d 559 to_process -= m_socket->LastCount();
c3bcb48f 560 LogWorker(wxString::Format("ThreadWorker: %d bytes written, %d todo",m_socket->LastCount(),to_process));
2804f77d
VZ
561 }
562 while(!m_socket->Error() && to_process != 0);
563 }
564
c3bcb48f 565 LogWorker("ThreadWorker: done");
2804f77d
VZ
566 e.m_workerFailed = to_process != 0;
567 m_socket->Destroy();
568 wxGetApp().AddPendingEvent(e);
569 return 0;
570}
571
572EventWorker::EventWorker(wxSocketBase* pSock)
573 : m_socket(pSock),
574 m_inbuf(NULL),
575 m_infill(0),
576 m_outbuf(NULL),
577 m_outfill(0)
578{
579 m_socket->SetNotify(wxSOCKET_LOST_FLAG|wxSOCKET_INPUT_FLAG|wxSOCKET_OUTPUT_FLAG);
580 m_socket->Notify(true);
581 m_socket->SetEventHandler(*this);
582 m_socket->SetFlags(wxSOCKET_NOWAIT);
583 m_socket->GetPeer(m_peer);
584}
585
e2bcc781
VZ
586EventWorker::~EventWorker()
587{
2804f77d
VZ
588 m_socket->Destroy();
589 delete [] m_inbuf;
590 delete [] m_outbuf;
591}
592
593void
e2bcc781 594EventWorker::DoRead()
2804f77d
VZ
595{
596 if (m_inbuf == NULL)
597 {
598 //read message header
599 do
600 {
0f359e5c 601 m_socket->Read(m_signature + m_infill, 2 - m_infill);
e2bcc781
VZ
602 if (m_socket->Error())
603 {
2804f77d
VZ
604 if (m_socket->LastError() != wxSOCKET_WOULDBLOCK)
605 {
c3bcb48f 606 LogWorker(wxString::Format("Read error (%d): %s",m_socket->LastError(),GetSocketErrorMsg(m_socket->LastError())),wxLOG_Error);
2804f77d
VZ
607 m_socket->Close();
608 }
609 }
610 else
611 {
612 m_infill += m_socket->LastCount();
e2bcc781
VZ
613 if (m_infill == 2)
614 {
2804f77d
VZ
615 unsigned char chunks = m_signature[1];
616 unsigned char type = m_signature[0];
617 if (type == 0xCE)
618 {
c3bcb48f 619 LogWorker("This server does not support test2 from GUI client",wxLOG_Error);
2804f77d
VZ
620 m_written = -1; //wxSOCKET_LOST will interpret this as failure
621 m_socket->Close();
622 }
623 else if (type == 0xBE || type == 0xDE)
624 {
625 m_size = chunks * (type == 0xBE ? 1 : 1024);
626 m_inbuf = new char[m_size];
627 m_outbuf = new char[m_size];
628 m_infill = 0;
629 m_outfill = 0;
630 m_written = 0;
c3bcb48f 631 LogWorker(wxString::Format("Message signature: len: %d, type: %s, size: %d (bytes)",chunks,type == 0xBE ? "b" : "kB",m_size));
2804f77d 632 break;
0f359e5c
VZ
633 }
634 else
2804f77d 635 {
c3bcb48f 636 LogWorker(wxString::Format("Unknown test type %x",type));
2804f77d
VZ
637 m_socket->Close();
638 }
639 }
640 }
641 }
642 while(!m_socket->Error() && (2 - m_infill != 0));
643 }
644
645 if (m_inbuf == NULL)
646 return;
647 //read message data
e2bcc781
VZ
648 do
649 {
650 if (m_size == m_infill)
651 {
2804f77d 652 m_signature[0] = m_signature[1] = 0x0;
5276b0a5 653 wxDELETEA(m_inbuf);
2804f77d
VZ
654 m_infill = 0;
655 return;
656 }
657 m_socket->Read(m_inbuf + m_infill,m_size - m_infill);
e2bcc781
VZ
658 if (m_socket->Error())
659 {
2804f77d
VZ
660 if (m_socket->LastError() != wxSOCKET_WOULDBLOCK)
661 {
c3bcb48f
VZ
662 LogWorker(wxString::Format("Read error (%d): %s",
663 m_socket->LastError(),
664 GetSocketErrorMsg(m_socket->LastError())),
665 wxLOG_Error);
2804f77d
VZ
666
667 m_socket->Close();
668 }
669 }
670 else
671 {
672 memcpy(m_outbuf+m_outfill,m_inbuf+m_infill,m_socket->LastCount());
673 m_infill += m_socket->LastCount();
674 m_outfill += m_socket->LastCount();
675 DoWrite();
676 }
677 }
678 while(!m_socket->Error());
679};
680
681void EventWorker::OnSocketEvent(wxSocketEvent& pEvent)
682{
683 switch(pEvent.GetSocketEvent())
684 {
685 case wxSOCKET_INPUT:
686 DoRead();
e2bcc781
VZ
687 break;
688
2804f77d 689 case wxSOCKET_OUTPUT:
7ea70b6f 690 if ( m_outbuf )
2804f77d 691 DoWrite();
e2bcc781
VZ
692 break;
693
2804f77d 694 case wxSOCKET_CONNECTION:
7ea70b6f 695 LogWorker("Unexpected wxSOCKET_CONNECTION in EventWorker", wxLOG_Error);
e2bcc781
VZ
696 break;
697
2804f77d 698 case wxSOCKET_LOST:
e2bcc781 699 {
7ea70b6f 700 LogWorker("Connection lost");
e2bcc781
VZ
701 WorkerEvent e(this);
702 e.m_workerFailed = m_written != m_size;
703 wxGetApp().AddPendingEvent(e);
704 }
705 break;
2804f77d
VZ
706 }
707}
708
e2bcc781
VZ
709void EventWorker::DoWrite()
710{
711 do
712 {
2804f77d
VZ
713 if (m_written == m_size)
714 {
5276b0a5 715 wxDELETEA(m_outbuf);
e2bcc781 716 m_outfill = 0;
c3bcb48f 717 LogWorker( "All data written");
e2bcc781 718 return;
2804f77d
VZ
719 }
720 if (m_outfill - m_written == 0)
721 {
722 return;
723 }
724 m_socket->Write(m_outbuf + m_written,m_outfill - m_written);
725 if (m_socket->Error())
726 {
727 if (m_socket->LastError() != wxSOCKET_WOULDBLOCK)
728 {
c3bcb48f 729 LogWorker(
e2bcc781 730 wxString::Format("Write error (%d): %s",
2804f77d
VZ
731 m_socket->LastError(),
732 GetSocketErrorMsg(m_socket->LastError())
733 )
e2bcc781 734 ,wxLOG_Error
2804f77d
VZ
735 );
736 m_socket->Close();
737 }
738 else
739 {
c3bcb48f 740 LogWorker("Write would block, waiting for OUTPUT event");
2804f77d
VZ
741 }
742 }
743 else
744 {
745 memmove(m_outbuf,m_outbuf+m_socket->LastCount(),m_outfill-m_socket->LastCount());
746 m_written += m_socket->LastCount();
747 }
c3bcb48f
VZ
748 LogWorker(wxString::Format("Written %d of %d bytes, todo %d",
749 m_socket->LastCount(),m_size,m_size - m_written));
2804f77d
VZ
750 }
751 while (!m_socket->Error());
752}
753
754BEGIN_EVENT_TABLE(EventWorker,wxEvtHandler)
e2bcc781 755 EVT_SOCKET(wxID_ANY,EventWorker::OnSocketEvent)
2804f77d 756END_EVENT_TABLE()