I am trying to write a sort of chat program. However, right now the client can only recieve messages until it has sent one because std::cin must wait until the client has pressed enter. Is there an alternative to this?
Thanks.
#include <SFML/Network.hpp>#include <iostream>void DoClientTCP(unsigned short Port){ // Create a TCP socket for communicating with server sf::SocketTCP Client; sf::IPAddress Address = sf::IPAddress::GetPublicAddress(); // Connect to the specified server if(Client.Connect(Port, Address) == sf::Socket::Done){ std::cout << "Connected to server " << Address << std::endl; } std::string message; while(1){ std::cin >> message; // Send the message sf::Packet packet; packet << message; if(Client.Send(packet) == sf::Socket::Done){ std::cout << "Message sent to server : \"" << message << "\"" << std::endl; } if(Client.Receive(packet) == sf::Socket::Done){ packet >> message; // Show it std::cout << "Message received from server : \"" << message << "\"" << std::endl; } } // Close the socket when we're done Client.Close();}
Append individual keypresses to the message and send when character==Return.
You'll also have to poll for receiving or you won't be able to send multiple messages until a message is received.
EDIT: I understand, if you've never done threads, writing multiple thread code is not a fun thing to learn/test. However, if you're going to play with sockets, that's really the best path to take.
[Edited by - Buckeye on July 9, 2010 7:19:43 AM]
Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.
You don't forget how to play when you grow old; you grow old when you forget how to play.
If you're using Windows you can catch the keypress events as they happen and append those characters to the message until the user presses return or whatever is your send key at which point you can send the message and clear the current message buffer.
I don't think it's that easy on non-Windows systems. The header <curses.h> does exist on many systems, but as far as I know it's not compatible with <conio.h> (e.g., no kbhit(), you have to change the terminal to non-delay mode...).
If platform independence is important, it can probably be achieved by using SDL.