我之前尝试过查看这个问题,但不幸的是,似乎没有答案。
我的错误是:
ac@universe $ g++ -std=c++14 Bot.cpp ServerSocket.cpp ../shared/Socket.cpp server.cpp
In file included from /usr/include/c++/5.3.0/thread:39:0,
from server.cpp:4:
/usr/include/c++/5.3.0/functional: In instantiation of ‘struct std::_Bind_simple<void (*(ServerSocket))(ServerSocket&)>’:
/usr/include/c++/5.3.0/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(ServerSocket&); _Args = {ServerSocket&}]’
server.cpp:55:44: required from here
/usr/include/c++/5.3.0/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(ServerSocket))(ServerSocket&)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/5.3.0/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(ServerSocket))(ServerSocket&)>’
_M_invoke(_Index_tuple<_Indices...>)
^
他们正在谈论的服务器代码是:
#include "ServerSocket.h"
#include "Bot.h"
#include <thread>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include "../shared/SocketException.h"
#define PORT 23700
using namespace std;
int bot_id = 0;
unordered_map<int, Bot*>botlist;
void start_bot(ServerSocket& sock){
try{
string data; string command;
while(true){
sock >> data;
cout << "Bot reply: " << data << endl;
cout << ">" ;
getline(cin, command);
sock << command;
}
}catch(SocketException&){}
}
//starts the server on specified address and port
void start(){
try {
ServerSocket server (PORT);
while (true){
Bot new_bot(++bot_id);
server.accept(new_bot.socket());
botlist.insert(make_pair(bot_id,&new_bot));
thread newbot(start_bot,new_bot.socket());
}
}catch (SocketException& e){
cout << "Socket Exception: " << e.description() << endl;
}
}
int main(){
start();
return 0;
}
我认为我在做线程的根本错误。基本上,我想要做的是,无论何时客户端连接服务器(此代码),我都会启动一个新线程。 start_bot()是被调用以为每个客户端启动新线程的函数,start()通常在端口上启动服务器。