SFML networking C++ client wont connect - c++

Currently I am trying to learn SFML networking but I am having a problem with the client (I think).
#include <iostream>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
int main()
{
sf::TcpSocket sock;
sf::Packet backpack;
sf::Thread Thread;
std::cout <<"Attempting to connect to server" << std::endl;
sf::Socket::Status status = sock.connect("127.0.0.1", 25568);
if (status != sf::Socket::Done){
std::cout << "Could Not Connect to server" << std::endl;
} else {
std::cout << "Connected to server" << std::endl;
}
backpack << 9;
std::cout << "Sending data" << std::endl;
sock.send(backpack);
std::cout << "Sent the data" << std::endl;
std::cout << "Client task completed" << std::endl;
return 0;
}
Here is The server code
#include <iostream>
#include <SFML/Network.hpp>
int main()
{
std::cout << "Server Has started" << std::endl;
sf::TcpSocket peer;
sf::TcpListener ear;
sf::Packet backpack;
if (ear.listen(25568) != sf::Socket::Done){
std::cout << "Listerner failed to be setup, another program may be using that port." << std::endl;
} else {
std::cout << "Server is ready" << std::endl;
}
if (ear.accept(peer) != sf::Socket::Done){
std::cout << "Client refused connection" << std::endl;
} else {
std::cout << "Client connection Accepted" << std::endl;
}
peer.receive(backpack);
std::cout << "Data recieved" << std::endl;
int num;
backpack >> num;
std::cout << num << std::endl;
std::cout << "hello world" << std::endl;
return 0;
}
When running the server and client (In either order) The client will output nothing after the message "Attempting to connect to server" appears, And the server outputs nothing after the message "Server is ready" Please help =) I have been stuck on this problem for a while.

Related

Socket issue when include mutex C++

I write a program, that should create a server using a socket in a extra thread. This works well, until I #include <mutex> to my application. But I need to include mutex for another function (not in the example here).
When I include mutex, I get this error when calling bind (marked in code):
error C2440: '=': cannot convert 'std::_Bind' to 'long' in (PATH_TO_PROJECT_LINE_WHERE_BIND_IS_CALLED)
Here is my code:
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib,"ws2_32.lib")
#include <cstdio>
#include <WinSock2.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <process.h>
#include <mutex> //if I do not include mutex, everything works
using namespace std;
unsigned int __stdcall threadCreateServer(void*data){
long res;
WSADATA wsaData;
res = WSAStartup(MAKEWORD(2, 0), &wsaData);
if (res == 0){
cout << "[CreateServer] " << "WSAStartup successful" << endl;
}
else {
cout << "[CreateServer] " << "Error WSAStartup" << endl;
return -201;
}
SOCKET slisten, client;
slisten = socket(AF_INET, SOCK_STREAM, 0);
if (slisten != INVALID_SOCKET){
cout << "[CreateServer] " << "Socket() successful" << endl;
}
else{
cout << "[CreateServer] " << "error Socket" << endl;
return -202;
}
sockaddr_in info;
info.sin_addr.s_addr = inet_addr("127.0.0.1");
info.sin_family = AF_INET;
info.sin_port = htons(54126);
res = bind(slisten, (struct sockaddr*)&info, sizeof(info)); //ERROR HERE
if (res != SOCKET_ERROR){
cout << "bind successful" << endl;
}
else {
cout << "ERROR bind" << endl;
return -203;
}
res = listen(slisten, 1);
if (res != SOCKET_ERROR){
cout << "[CreateServer] " << "Listen successful" << endl;
}
else {
cout << "[CreateServer] " << "Listen error" << endl;
return -204;
}
sockaddr_in clientinfo;
int clientinfolen = sizeof(clientinfo);
cout << endl << "~~~~~~~~~" << endl << "[CreateServer] " << "Please connect a client to " << inet_ntoa(info.sin_addr) << ":" << ntohs(info.sin_port) << endl << "~~~~~~~~~" << endl;
client = accept(slisten, (struct sockaddr*)&clientinfo, &clientinfolen);
if (client != SOCKET_ERROR){
cout << "[CreateServer] " << "Client accepted " << inet_ntoa(clientinfo.sin_addr) << ":" << ntohs(clientinfo.sin_port) << endl;
}
else{
cout << "[CreateServer] " << "ERROR client not accepted" << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handleThreadCreateServer=(HANDLE)_beginthreadex(0,0,&threadCreateServer,0,0,0);
WaitForSingleObject(handleThreadCreateServer, INFINITE);
CloseHandle(handleThreadCreateServer);
return 0;
}
As proposed in a comment, I cannot do using namespace std, because there would be conflicting functions when including mutex.
For everyone, who will have this problem, too:
//to not using namespace std, but:
using std::cout;
using std::endl;
using std::string;
For every other function that isn't used until now, a similar line has to be added. There is not possibllity of using the namespace std and "unusing" std::mutex.

Incorrect Data From CallNtPowerInformation(SystemPowerInfomation…)?

Trying to get some data from CallNtPowerInformation(SystemPowerInfomation…) but the returned data doesn't seem to be correct (lidpresent should be true but it's false, VideoDimPresent should be false but it's true..) I'm new to C++ and I'm pretty sure I'm doing something wrong.
My code:
#include <NTstatus.h>
#define WIN32_NO_STATUS
#include <windows.h>
#include <Powrprof.h>
#include <iostream>
#pragma comment(lib, "Powrprof.lib")
int main()
{
SYSTEM_POWER_CAPABILITIES spwr;
NTSTATUS status = ::CallNtPowerInformation(SystemPowerInformation, NULL, 0, &spwr, sizeof(SYSTEM_POWER_CAPABILITIES));
if(STATUS_SUCCESS == status){
if(spwr.LidPresent){
std::cout << "LidPresent TRUE!" << std::endl;
}else{
std::cout << "LidPresent FALSE!" << std::endl;
}
if(spwr.VideoDimPresent){
std::cout << "VideoDimPresent TRUE!" << std::endl;
}else{
std::cout << "VideoDimPresent FALSE!" << std::endl;
}
if(spwr.SystemS1){
std::cout << "SystemS1 TRUE!" << std::endl;
}else{
std::cout << "SystemS1 FALSE!" << std::endl;
}
if(spwr.SystemS2){
std::cout << "SystemS2 TRUE!" << std::endl;
}else{
std::cout << "SystemS2 FALSE!" << std::endl;
}
if(spwr.SystemS3){
std::cout << "SystemS3 TRUE!" << std::endl;
}else{
std::cout << "SystemS3 FALSE!" << std::endl;
}
if(spwr.SystemS4){
std::cout << "SystemS4 TRUE!" << std::endl;
}else{
std::cout << "SystemS4 FALSE!" << std::endl;
}
}
else
{
std::cout << "CallNtPowerInformation failed. Status: " << status << std::endl;
}
return status;
}
You passed SystemPowerInformation, so lpOutputBuffer is expected to point to SYSTEM_POWER_INFORMATION structure.
You may want to pass SystemPowerCapabilities rather than SystemPowerInformation if you expect SYSTEM_POWER_CAPABILITIES.
See CallNtPowerInformation documentation.

How to correctly login into xmpp server with libjingle

I have a piece of code, quite basic, for logging in into an xmpp server in libjingle.
I cannot log in into the server. I am sure that the parameters are correct since I checked with an xmpp client program.
My sequence is like this:
Create XmppPump.
Setup callback for xmppPump.client().SignalStateChange, which should be called when progress is done through the different states in XmppEngine.
Start the signaling thread and block on a future that will be unblocked when XmppPump::DoLogin is done.
buzz::XmppClient * xmppClient = mI->xmppPump.client();
assert(xmppClient != nullptr);
buzz::Jid jid = buzz::Jid(user);
std::string server = serverHost + ":" +
std::to_string(kXmppClientDefaultPort);
bool allow_plain = true;
buzz::XmppClientSettings xcs;
xcs.set_user(jid.node());
xcs.set_resource(jid.resource());
xcs.set_host(jid.domain());
xcs.set_allow_plain(allow_plain);
xcs.set_use_tls(buzz::TLS_DISABLED);
talk_base::InsecureCryptStringImpl pass;
pass.password() = password;
xcs.set_pass(talk_base::CryptString(pass));
std::string server_;
int port;
std::size_t colon = server.find(':');
if (colon == std::string::npos) {
server_ = server;
port = kXmppClientDefaultPort;
}
else {
server_ = server.substr(0, colon);
port = atoi(server.substr(colon + 1).c_str());
}
std::cout << "Logging in as user " << jid.node() << std::endl;
std::cout << "User domain is " << jid.domain() << std::endl;
std::cout << "Resource is " << jid.resource() << std::endl;
std::cout << "Password is " << password << std::endl;
std::cout << "Logging into server " << server_;
std::cout << " port " << port << std::endl;
xcs.set_server(talk_base::SocketAddress(server_, port));
xcs.set_protocol(cricket::PROTO_SSLTCP);
talk_base::InitializeSSL();
std::future<buzz::XmppEngine::State> result =
mI->xmppLoginState.get_future();
//Callback is setup here
xmppClient->SignalStateChange.connect(mI.get(),
&Impl::OnStateChange);
std::cout << std::endl;
std::cout << "About to call buzz::XmppPump::DoLogin " << std::endl;
//Logging in async.
mI->xmppPump.DoLogin(xcs, new buzz::XmppSocket(buzz::TLS_DISABLED), nullptr);
std::cout << "Called buzz::XmppPump::DoLogin " << std::endl;
mI->signalingThread.Start();
std::cout << "Blocked waiting for buzz::xmppPump::DoLogin to finish."
<< std::endl;
//Forever here and XmppEngine::STATE_STARTED always.
result.get();
std::cout << "buzz::XmppPump::DoLogin finished.";

Poco multicast pair example

I have these two poco programs, one sends the other receives. The receive doesn't crash, but I can't get the send to work. Sadly, the exception is not very helpful either, just saying "Net Exception". It might have to do with running both programs on the same machine, but still, the reuse address is set to true and so is the loopback.
//Receive
#include <string>
#include <iostream>
// MulticastSocket receive example
#include <Poco/Net/SocketAddress.h>
#include <Poco/Net/MulticastSocket.h>
using namespace std;
int main(int argc, char* argv[])
{
Poco::Net::initializeNetwork();
std::cout << "1" << std::endl << std::flush;
//Poco::Net::SocketAddress localAddr(Poco::Net::IPAddress(), 1900);
Poco::Net::SocketAddress localAddr("239.255.255.250", 1900);
std::cout << "2" << std::endl << std::flush;
Poco::Net::MulticastSocket socket(localAddr, true);
std::cout << "3" << std::endl << std::flush;
socket.setLoopback(true);
std::cout << "4" << std::endl << std::flush;
socket.setTimeToLive(4);
std::cout << "5" << std::endl << std::flush;
Poco::Net::SocketAddress groupAddr("239.255.255.250", 1900);
std::cout << "6" << std::endl << std::flush;
socket.joinGroup(groupAddr.host());
std::cout << "7" << std::endl << std::flush;
Poco::Net::SocketAddress sender;
char buffer[512];
int n = socket.receiveFrom(buffer, sizeof(buffer), sender);
std::cout << buffer << std::endl << std::flush;
Poco::Net::uninitializeNetwork();
return 0;
}
//Send
#include <string>
#include <iostream>
#include <Poco/Net/SocketAddress.h>
#include <Poco/Net/MulticastSocket.h>
#include <Poco/Net/NetException.h>
using namespace std;
using namespace Poco;
int main(int argc, char* argv[])
{
Poco::Net::initializeNetwork();
try
{
Poco::Net::SocketAddress address("239.255.255.250", 1900);
//Poco::Net::SocketAddress address(Poco::Net::IPAddress(), 1900);
std::cout << "1" << std::endl << std::flush;
Poco::Net::MulticastSocket socket(address, true);
std::cout << "2" << std::endl << std::flush;
socket.setLoopback(true);
std::cout << "3" << std::endl << std::flush;
//Poco::Net::SocketAddress sender;
char buffer[512];
buffer[0] = 'H';
buffer[1] = '\0';
std::cout << "Sending " << buffer << std::endl;
//socket.sendTo(buffer, 512, sender);
socket.sendBytes(buffer, 512, 0);
std::cout << "4" << std::endl << std::flush;
}
catch(const Poco::Net::NetException& ex)
{
std::cout << ex.what() << std::endl << std::flush;
}
Poco::Net::uninitializeNetwork();
return 0;
}
You have to bind to the IP of your computer and not the IP of the multicast group. You have commented the correct line out:
Poco::Net::SocketAddress localAddr(Poco::Net::IPAddress(), 1900);
Try looking at the MulticastEchoServer example that comes with Poco. It is under Net/testsuite/src/MulticastEchoServer.cpp in the sources.

mysqlpp connect method timeout - how can I control it?

I'm trying to control the connect method timeout, but I didn't find the appropriate mean.
Just to be clear, I'm not talking about the Idle connection timeout(ConnectTimeoutOption).
The scenario I need to deal with is a database gone away, and my server has to cope with that. My current handling of things is that I'm pinging the server, and If I notice that the ping failed, I'm suspending the queries for 100 seconds. After that I'm trying to reestablish the connection. The problem is that if the database is still dead, than the connect method takes about 20 seconds to answer (can be simulated by just pulling the network cable), which is way too much for me.
This should work for you
#include <mysql++.h>
#include <cstdio>
int main()
{
mysqlpp::Connection conn;
conn.set_option(new mysqlpp::ReconnectOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(5));
const std::string db="mysql_cpp_data";
const std::string query_text="SELECT count(*) as total FROM stock";
conn.connect(db.c_str(), "somehost", "user", "pass");
try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
}
std::cout << "Make database go away now and press a key\n";
getchar();
try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
std::cout << "Make database come back now and press a key\n";
getchar();
while(!conn.ping())
{
sleep(1);
std::cout << "Waiting for DB to come back\n";
}
if(!conn.select_db(db))
{
std::cout << "Failed to change DB\n";
}
}
try
{
mysqlpp::Query query=conn.query();
query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << " " << e.errnum() << std::endl;
}
return 0;
}
try this out.
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmdline.h>
#include <mysql++.h>
#define DBS "library"
#define USR "root"
#define PAS "rootsman"
using namespace std;
using namespace mysqlpp;
int main(int argc, char *argv[]) {
//for true cgi but in this case it works, kind of baffling!
mysqlpp::examples::CommandLine cmdline(argc, argv, USR, PAS);
if (!cmdline) return 1;
mysqlpp::Connection conn(true);
conn.set_option(new mysqlpp::ReconnectOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(5));
conn.connect(DBS, cmdline.server(), cmdline.user(), cmdline.pass());
try {
mysqlpp::String sql("select firstname from person");
mysqlpp::Query query = conn.query(sql);
mysqlpp::StoreQueryResult res = query.store();
mysqlpp::StoreQueryResult::const_iterator it;
int count = 1;
for (it = res.begin(); it != res.end(); ++it) {
mysqlpp::Row row = *it;
cout << count << "\t" << row[0] << endl;
++count;
}
} catch (const mysqlpp::BadQuery& bq) {
cerr << "query error: " << bq.what() << endl;
return -1;
}
cout << "\nmake database fly away now by pressing a key>" << endl;
getchar();
try {
mysqlpp::Query query = conn.query();
mysqlpp::String sql("select count(*) as total from person");
query << sql;
mysqlpp::StoreQueryResult res = query.store();
cout << "has " << (*res.begin())[0] << " rows" << endl;
} catch (mysqlpp::BadQuery& e) {
cerr << "\n bad query 2>" << e.what() << endl;
cout << "\nmake database fly back now by pressing enter>" << endl;
while (!conn.ping()) {
//sleep(1);
cout << "\nwaiting for database to fly back>" << endl;
}
if (!conn.select_db(DBS)) {
cerr << "\nfailed to reconnect" << endl;
}
}
try {
mysqlpp::Query query = conn.query();
//this is how my relation and its attributes looks like
String sql("insert into person(firstname,lastname,gender,love,angry,"
"forgiving) values('joy57/qxx','crimson','male','high','medium','high');");
query << sql;
query.execute();
cerr << "\n **inserted successfully**\n" << endl;
} catch (mysqlpp::BadQuery& e) {
cerr << "bad query 3>" << e.what() << e.errnum() << endl;
return -1;
}
cerr << "Jesus helps me when i stumble and fall" << endl;
return 0;
}