 ~Sockets~
|
C++ Socket library tutorial
|
|
Sending data
Mission: Creating a socket that sends some text to DisplaySocket.
SendSocket.h
#ifndef _SENDSOCKET_H
#define _SENDSOCKET_H
#include <TcpSocket.h>
class SendSocket : public TcpSocket
{
public:
SendSocket(ISocketHandler& h) : TcpSocket(h) {}
SendSocket(ISocketHandler& h, const std::string& data) : TcpSocket(h), m_data(data) {}
void OnConnect() {
SetLineProtocol();
if (m_data.empty())
Send("Random text.\n");
else
Send(m_data + "\n");
}
private:
std::string m_data;
};
#endif // _SENDSOCKET_H
|
|
The main() program.
We want to use DisplaySocket to listen for incoming connections, and our
SendSocket to send some random data.
send_test.cpp
#include <SocketHandler.h>
#include <ListenSocket.h>
#include "DisplaySocket.h"
#include "SendSocket.h"
int main(int argc, char *argv[])
{
SocketHandler h;
ListenSocket<DisplaySocket> l(h);
std::string text = argc > 1 ? argv[1] : "";
l.Bind(12346);
h.Add(&l);
SendSocket sock(h, text);
sock.Open("localhost", 12346);
h.Add(&sock);
while (h.GetCount())
{
h.Select(1, 0);
}
}
|
|
|