I’m trying to work with sockets in C++. The only work with sockets I have ever done was in Java (I created an IRC bot, to be specific) and the code I used looked like the following –
Socket socket = new Socket(host, port);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReater(
new InputStreamWriter(socket.getInputStream()));
then for my bot to read I would get a new thread and initiate a while loop –
String line;
while((line = reader.readLine()) != null) ...
And to write –
writer.write(text);
writer.flush();
Now I’m attempting to do so in C++ and things are of course at a lower level and I don’t quite understand what I’m doing. I looked for some tutorials on using winsock.h and tried them all to no avail. A friend of mine recommended the socket library sdl_net.
My question is how would my code in C++ look different compared to the code I used for my IRC bot in Java? Also, what is the difference between the “Buffered” streams in Java and my lower-level socket work in C++?
To answer your main question, this tutorial shows you roughly what the C++ would look like:
http://www.linuxhowtos.org/C_C++/socket.htm
http://www.linuxhowtos.org/data/6/client.c
Fundamentally, you need to use the
socket()andconnect()calls to instead ofnew Socket().The C++ streams are similar to the raw
socket.get(Output|Input)Stream()streams in that there is no buffering being performed. TheBuffered(Output|Input)Streamstores the written/read bytes in a buffer instead of writing through to the underlying stream for every call towrite()/read(). Callingflush()forces the buffered data to be written through.