I'm new to c++ and I started to code my server with boost. I follow a lot of example on the web and on the official doc. But i found nothing (maybe I don't ask the good question) about this-> communicate with a specific client. By this I mean that->
old question:
Server launch and wait for connection-> client(1) connect through
TCP-> server accept client and start async_read
Let's say 3 clients also connect->
How I'll tell to my server too write too client(2) or (3) but not
both?
I express myself badly
New question:
My server work fine, when client send data to server (custom client in Unreal engine 4) he can read it then write back to my client with no problem. I search a way to speak to the client I want without needed him to send data. Example:
client 1 write to server-> the data send to server launch the next action-> write to a specific client.
More specific example:
Client 1 want to send request to client 10, so client 1 write to the server the action «action, id client» (request, 10) then the server know that he need to talk to the client 10 and send request.
My problem is not on the client side, but on the server side.
I'm sure it's pretty easy and I just don't understand some basic stuff, if someone could provide me a direction, an example or simply an explanation it would be appreciated. Thanks for future answer.
EDIT:
If somebody have hard time like me (I know it's easy but we never know :p, maybe it could help someone) here the answer.
I include this inside the file where I use to connect, write, send, etc.
std::map<int, tcp::socket> playerRemote;
I set it->
playerRemote.insert(std::pair<int, tcp::socket>(id, std::move(socket_)));
use the socket->
boost::asio::async_read(playerRemote.at(id_to_use)
Question resolve! thanks for help!
Every time that your server program did an accept it got a new socket with a new client on the other end of it.
The usual practice is to have some kind of object which you create and initialize with this new socket. And then you put that object into some kind of structure. Like a set, a map, a vector, a list, anything really.
When you want a particular client then search that data structure for it. If you used a map or a unordered_map then you can get it quickly by whatever key you used.
Now you have your client object you can call a method on it. Like your own version of "send" which can add it to a per-client buffer. Since message sending is asynchronous in Boost ASIO (it's right there in the name) you know you may not be able to send it right away.
The Boost ASIO chat example application is good about this.
Look at the link that The Quantum Physicist put in comments. Especially this one: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/chat/chat_server.cpp
Related
First, I want to say that I'm new with Boost asio, and I see a lot of examples but it remains things I don't understand.
I want to create a server, that will accept two clients (it will use two socket). The first client will send messages to the server and the server will send this message to the other client (yes, it is useless to use a server, but it's not the point here, I want to understand how all this work). This will happen until one of the client close.
So, I created a server, the server wait for the clients, and then, it must wait for the first client to send some message. And this is my question: what must I do after?
I thought I need to read the first socket, and then write on the second, and so and so, but how I know if the first client writed on the socket? Same, how I know if the second client read the second socket?
I don't need code, I just want to know the good way to do that.
Thanks a lot for reading!
When you perform async_read you specifify a callback which is going to be called whenever any data is read to the buffer ( you should provide the buffer also, check the async_read's documentation ). Respectively you should provide callback for the async_write to know when your data is already sent. So, from the server perspective, for the client which 'writes' you should do async_read, and for the second client which 'reads' you should do async write. With the offered dataflow client1->server->client2 it is hard to recognize which client the server should read from and which one is write to. It's up to you. You can choose the first connected client as writer and the second as reader, for example.
You might want to start with asio iostreams. It's a high-level iostream-like abstraction above asynchronous sockets.
P.S.: also, don't forget to run io_service.run() loop somewhere. Because all the asio callbacks are executed within that loop.
I'm really new to this whole socket and server development, I'm not yet familiar with how it all works.
I made a simple flash application that needs to communicate with a socket,
With that, I used a socket that supports AS3 and works on "Red Tamarin",
Well I'll get to the point:
I currently have a loop that always runs socket.receive()
It responds and even displays text that I send from my flash application.
My goal is to get a simple online flash game,
Probably use SQL / SQLite to save information and export it to players,
What I don't understand is how I can take it there..
What I thought I'll need to do is something like so:
On the server side:
Have a loop that runs as long as the server is alive, that loop should always check every connection it has with clients and wait for commands coming from them, such as log in, update player position, disconnect, request list of objects in given positions
Client side:
Send information to the server according to the action, like when a player moves, send the new position to the server in a similar way to this : "MovePlayer[name][x][y]"
Is my plan really how things should be?
And about the actual information being sent, I'm curious, will it be efficient to constantly send the server string data? (that's what I'm used to work with, not some weird bytes and stuff)
Thanks in advance!
You're on the right track. But I encourage you to first define a communication protocol. You can start by defining what a command looks like. For example:
COMMAND <space> PARAM1 <space> PARAM2 <line-break>
A few considerations on the protocol definition:
What if PARAM1 is a string and contains spaces? How can you tell the start and end of each parameter?
Your parameters could also contain a line-break.
If your client application is installed by your clients, they'll need to update it once in a while. To complicate even further, they may run an older version and expect it to work, even if you have changed your protocol. This imposes a need for protocol versioning. Keep that in mind if you require user interaction for updating the client part of your application.
These are the most fundamental considerations I can think for your scenario. There may be other important considerations, but most of them depend on how your game works. Feel free to amend my list if you think I forgot something OP should consider.
After defining what a command looks like, document all commands you believe your applications needs. Don't segregate definition of a command unless it becomes too complex or excessively long for some of your operations. Try to keep things simple.
Now back to your questions:
Is my plan really how things should be?
Yes. That's exactly how it should be.
And about the actual information being sent, I'm curious, will it be efficient to constantly send the server string data? (that's what I'm used to work with, not some weird bytes and stuff)
That depends on a number of factors:
Which protocol you're using (TCP, UDP, etc);
Number of concurrent clients;
Average time to process a command;
Do you broadcast updates to other players?
How you did implement your server application;
Physical contraints:
Hardware: CPU, memory, etc;
Network: bandwidth, latency, etc;
(source: it20.info)
look at this
https://code.google.com/p/spitfire-and-firedrop/
there you will see the basic of building a socket server with redtamarin
see in particular
https://code.google.com/p/spitfire-and-firedrop/source/browse/trunk/spitfire/src/spitfire/Server.as
the details is as follow, redtamarin basically use blocking sockets with select()
with a max hard coded FD_SETSIZE of 4096
see:
https://code.google.com/p/redtamarin/wiki/Socket#maxConcurrentConnection
so here what happen in your server loop
you basically have an array of sockets object
you loop every x milliseconds and for each socket
you ask if you can read it
if you can read on the socket, you then compare if this socket obj is the server
if it is the server that means you have a new connection
if not that means a client try to send you data and so you read this data
and then pass it to an "interpreter"
later in the same loop you check if the socket obj is still valid
and if you can write to it
if you can write and the socket object is not the server
then you can send data to the client
here the equivalent code in C for reference
http://martinbroadhurst.com/source/select-server.c.html
http://www.lowtek.com/sockets/select.html
for a very basic example look at socketpolicyd
https://code.google.com/p/spitfire-and-firedrop/wiki/socketpolicyd
https://code.google.com/p/spitfire-and-firedrop/source/browse/trunk/socketpolicyd/src/spitfire/SocketPolicyServer.as
and compare the implementation with Perl and PHP
http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
My situation: I would like to create a hobby project for improving my C++ involving real-time/latency programming.
I have decided I will write a small Java program which will send lots of random stock prices to a client, where the client will be written in C++ and accept all the prices.
I do not want the C++ client to have to poll/have a while loop which continuously checks for data even if there is none.
What options do I have for this? If it's easier to accomplish having a C++ server then that is not a problem.
I presume for starters I will have to use the boost ASIO package for networking?
I will be doing this on windows 7.
Why not just have the Java server accept connections and then wait for some duration of time. e.g. 10 seconds. Within that time if data becomes available, send it and close the connection.
Then the C++ client can have a thread which opens a connection whenever the previous one has completed.
That should give quite low latency without creating connections very often when there is no new data.
This is basically the Comet web programming model, which is used for many applications.
Think about how a web server receives data. When a URL is accessed the data is pushed to the server. The server need not poll the client (or indeed know anything about the client other than its a service pushing bytes towards it).
You could use a Java servlet to accept the data over HTTP and write the code in this fashion. Similarly, boost::asio has a server example that should get you started. Under the hood, you could enable persistent HTTP so that the connections aren't opened / closed frequently. This'll make the coding model much simpler.
I do not want the C++ client to have to poll/have a while loop which
continuously checks for data
Someone HAS to.
Need not be you. I've never used boost ASIO, but it might provide a callback registration. If yes, then just register a callback function of yours with boost, boost would do the waiting and give you a call back when it gets some data.
Other option is of course that you use some functions which are synchronous. Like (not a real function) Socket.read() which blocks the thread until there is data in the socket or it's closed. But in this case you're dedicating a thread of your own.
--edit--
Abt the communication itself. Just pick any IPC mechanism (sockets/pipes/files/...), someone already described one I think. Once you send the data, the data itself is "encoded" and "decoded" by you, so you can create your own protocol. E.g. "%%<STOCK_NAME>=<STOCK_PRICE>##" where "%%", = and ## (markers to mark start, mid and end) that you add on sender side and remove on receiver side to get stock name and price.
You can develop the protocol further based on your needs. Like you can also send buy/sell recommendation or, text alert msgs with major stock exchange news. As long as your client and server understand how the data is "encoded" you're good.
Finally, if you want to secure teh communication (and say you're not using some secure layer (SSL)) then you can encrypt the data. But that's a different chapter. :)
HTH
Firstly I think I need to say that I'm still learning C++ so apologies if this is blindingly obvious/simple.
I'm trying to use the libevent library (by trying I've looked through code in the sample folder and tested some) in my C++ program to consume an http stream. I'm wondering if anyone can provide me with an example of how I'd go about connecting to a URL e.g. live.domain.com, sending the appropriate headers, read the data returned and send data back over the same connection...
I'm not sure libevent does any blocking connections but just to be explicit, I'm after non-blocking samples.
Why am I trying to do this?
I'm using an API which requires you to open a connection and it keeps it alive unless there's an error. It'll periodically send status texts to the connected client until it receives a string with an ID over the same connection. At which point it starts sending data back about the ID given... I'm not entirely sure sending data back over the same connection after the initial request is strictly compliant but that's what the server expects so it'll work...if I knew how
Thanks in advance
Yuck. Given that this isn't really HTTP, I don't think you're going to be happy using a HTTP library - even if you get it to work today after a lot of frustration, it could easily be broken tomorrow. This is too rare to be a supported feature.
But...it sounds like it's also simple enough that you could just open a raw TCP connection with libevent, manually send something that looks kind of like an HTTP request, and handle it with raw sockets from there. You don't want the extra stuff a HTTP library gets you anyway (additional transfer/content encodings, proxy support, SSL, compatibility with other protocol versions, ...)
As far as examples go, look at the libevent book. In particular, the a "Trivial HTTP v0 client" that seems very close to what you want. Good luck!
I am new to quickfix (I'm a student trying to teach myself), and have downloaded the examples from quickfix.org (in c++) and have been able to connect ordermatch to tradeclient and get them talking to each other. I changed the config file for ordermatch to allow multiple clients and got that working (ordermatch can receive orders from multiple clients and manage the order book).
I have been trying to find a way to alter ordermatch to send it's confirm messages to ALL clients, not just the sender.
I have a seperate implementation of a limit orderbook and want to crack the incoming messages (orders, cancels, etc) and store them in my limit orderbook. My orderbook watches the book an makes trading decisions based on it. The problem is, I can't figure out how to get ordermatch to send all updates to this client. Further, I am having a hard time figuring out how to "soup up" the tradeclient to not only send orders, but receive and crack them.
I'm thinking I need to have an acceptor and an initator in each application(in ordermatch and in one of the tradeclients)--I've read this is possible and common but can't find any sample code. Am I on the right track here, or is there a better way to set this up? Does anybody have some sample code they can share? I am not planning on using this for live trading so crude code is perfectly fine by me.
Thanks in advance
Brandon
Same application can act as Initiator for one session and Acceptor for different session.
Infact you can have multiple Acceptor/Initiator sessions from same application.
Config file needs to define multiple sessions.
Or you can have separate config file for each session.
If I understand correctly, I think what you're trying to do is intercept messages between an OMS and a broker (c.f. client and server) and act depending on what they contain. There are a few ways you could do this, including intercepting at the TCP layer, but I think that the easiest way might be to use 2 separate programs as #DumbCoder suggests and connect to one of them as an acceptor from your clients, process the messages and then pass them on to another program via another protocol and then send them on from the other program. Theoretically you can create another instance of the engine in your program and, by using different config files on creation (when FIX::FileStoreFactory storeFactory(*settings); is called) of each instance of the engine. However, I have never seen this done and so feel that it could cause problems. If you do try this method I would strongly advise putting the initiator and the connector in different dlls which might just separate the two engine instances enough.