本文整理汇总了C++中ServerSocket类的典型用法代码示例。如果您正苦于以下问题:C++ ServerSocket类的具体用法?C++ ServerSocket怎么用?C++ ServerSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ServerSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1:
//
//finds the highest socket number and sets the rset and wset bits
//from our list of clients and our listening socket.
//
int
SimpleServer::getMaxFD()
{
int imax = m_sListen;
ServerSocket* s;
FD_ZERO(&m_wset);
FD_ZERO(&m_rset);
if(!m_bUsingThread)
{
//when we are using threads, this simple server object is only
//paying attention to one socket. Other simple server objects
//will pay attention to other sockets. Listen socket is taken
//care of in the manager.
FD_SET(m_sListen,&m_rset); //select on listening socket
}
for(s = m_listClients.getHead(); s; s = m_listClients.getNext())
{
FD_SET(*s,&m_rset); //select for readability
if(s->getOutBufferSize())
FD_SET(*s,&m_wset); //need to send data out, select for writability
if((int)(*s) > imax)
imax = *s;
}
return imax;
}
示例2: main
int main(int argc, const char * argv[])
{
m_g = make_shared<Game>(Game());
// start command consumer thread
thread consumer {consume_command};
// keep client threads here, so we don't need to detach them
vector<thread> handlers;
// create a server socket
ServerSocket server {machiavelli::tcp_port};
while (true) {
try {
while (true) {
// wait for connection from client; will create new socket
cerr << "server listening" << '\n';
unique_ptr<Socket> client {server.accept()};
// communicate with client over new socket in separate thread
thread handler {handle_client, move(client)};
handlers.push_back(move(handler));
}
} catch (const exception& ex) {
cerr << ex.what() << ", resuming..." << '\n';
} catch (...) {
cerr << "problems, problems, but: keep calm and carry on!\n";
}
}
return 0;
}
示例3: main
int main()
{
/*
StdWriteRead stdWriteRead;
runloop.registerReadIntent(fileno(stdin), &stdWriteRead);
runloop.run();
*/
/*
try
{
RunLoop runloop;
Socket socket;
socket.connect("localhost", 22, false);
int sock = socket.getSocket();
StdWriteRead stdWriteRead(sock);
runloop.registerReadIntent(sock, &stdWriteRead);
runloop.run();
}
catch ( std::runtime_error r )
{
fprintf(stderr, r.what());
}
*/
ServerSocket serverSocket;
serverSocket.listen("0.0.0.0", 3000, 10);
std::string ip;
serverSocket.accept(&ip, NULL);
printf("socket: %s\n", ip.c_str());
}
示例4: main
int main (int argc, char* argv[]) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &sig_handler;
sigaction(SIGINT, &sa, NULL);
IniParser* ini = new IniParser("server.ini");
documentRoot = ini->get("document_root");
std::string port = ini->get("port");
delete(ini);
ServerSocket* server = new ServerSocket(port);
ClientSocket* client = NULL;
while (!stop) {
client = server->accept(true);
if (client != NULL) {
pthread_t tid;
pthread_create(&tid, NULL, &clientThread, client);
pthread_detach(tid);
}
}
delete(server);
std::cout << "Shutdown complete." << std::endl;
return 0;
}
示例5: main
int main(){
Database db("database");
//listening requests
try{
// Create the socket
ServerSocket server ( 30000 );
while(true){
ServerSocket new_sock;
server.accept (new_sock);
try{
std::string data;
new_sock >> data;
std::string *res = db.request(data);
new_sock << *res;
delete res;
}catch (SocketException& e){
std::cout << "Something go wrong: " << e.description() << "\nExiting.\n";
}
}
}
catch (SocketException& e){
std::cout << "Something go wrong: " << e.description() << "\nExiting.\n";
}
return 0;
}
示例6: accept
bool accept(int port, string address = "0")
{
inactiveTime = 0;
ServerSocket* serverSocket = new ServerSocket();
socket = serverSocket;
return serverSocket->accept(port, address);
}
示例7: main
int main ( int argc, int argv[] )
{
std::cout << "running....\n";
try
{
// Create the socket
ServerSocket server ( 6006 );
while ( true )
{
ServerSocket new_sock;
server.accept ( new_sock );
try
{
while ( true )
{
char *data;
//new_sock >> data;
new_sock << "Mesaje";
}
}
catch ( SocketException& ) {}
}
}
catch ( SocketException& e )
{
cout << "Exception was caught:" << e.description() << "\nExiting.\n";
}
return 0;
}
示例8: Run
void LoginServer::Run(LoginServer *Instance)
{
ServerSocket runningSocket;
if (runningSocket.Configure(Instance->m_ServerPort) == false) {
printf("Unable to establish server socket, there is an issue with the server.\n");
return;
}
while (Instance->m_Running) {
/*
* Listen For New Connections.
*/
ClientConnection baseClient = runningSocket.Accept();
LoginClient* client = new LoginClient(baseClient);
/*
* Lock client array and place the client in the queue
*/
Instance->m_ClientsLock.lock();
Instance->m_Clients.push_back(client);
Instance->m_ClientsLock.unlock();
}
runningSocket.Flush();
}
示例9: throw
void IOUtil::createSocketPair(int pair[2]) throw (IOException&)
{
#if defined(WIN32)
Socket connectSocket;
Socket serverClientSocket;
ServerSocket listenSocket;
SocketAddress loopback = SocketAddress::loopback(AF_INET, 0);
listenSocket.listen(loopback, 5, false);
connectSocket.connect(listenSocket.getLocalAddress(), true);
if (!listenSocket.accept(serverClientSocket))
{
THROW2(IOException, "Can't accept for socket pair");
}
pair[0] = connectSocket.detach();
pair[1] = serverClientSocket.detach();
#else
if (0 != ::socketpair(AF_LOCAL, SOCK_STREAM, 0, pair))
{
THROW2(IOException, "Can't create socket pair");
}
#endif
}
示例10: main
int main (){
cout << "server running...." << endl;
try{
ServerSocket server ( 30000 ); // Create main server socket
while ( true ){ // server runs forever
ServerSocket new_sock; // bind user socket to port and listen
server.accept ( new_sock );
printUsage();
try{
while ( true ){
char command[256]; //user input
string reply; //command from client
cout << "> ";
cin.getline(command,256);
if (strlen(command) == 0) //re-prompt user if input is empty
continue;
new_sock << string(command); //send command to create
new_sock >> reply; //read confirmation
cout << reply <<endl;
}
}catch ( SocketException& ) {}
}
}
catch ( SocketException& e ){
cout << "Exception was caught:" << e.description() << endl << "Exiting.";
}
return 0;
}
示例11: handle_web_request
bool handle_web_request(void * args){
//get arguments
void **ar = (void **) args;
ServerSocket *serverSocket = (ServerSocket *) ar[0];
int client_file_descriptor = *((int *) ar[1]);
char *buffer = (char *) ar[2];
//=================================================
cout << "===========================" << endl;
cout << "raw data : " << buffer << endl;
//TODO:: optimize this (copy the whole buffer into string)
string data(buffer);
try{
ServerManager server_manager(data);
string response;
server_manager.handle_request(&response);
std::vector<char> writable(response.size()+1);
std::copy(response.begin(), response.end(), writable.begin());
writable[response.size()] = '\0';
//@Moustafa: please change to const char * instead of char *
serverSocket->writeToSocket(&writable[0], args);
HttpGetRequestParser request(data);
cout << "Required file : " << request.getRequiredFileName() << endl;
map<string,string> *m = request.getParameters();
map<string,string>::iterator it = m->begin();
cout << "parameters : " << endl;
for (;it != m->end();it++)
cout << it->first << " = " << request.getParameter(it->first) << endl;
}catch(int e){
return false;
}
//=================================================
//close the connection after returning the required object
if(serverSocket->getConnectionType() == SOCK_STREAM) close(client_file_descriptor);
return true;
}
示例12: sock
void KeyValueStore::InternalThread::incomingRoutine()
{
const Config::ServerInformation& info = config.getServerInformation();
Config::ThreadControl& control = config.getThreadControl();
Mutex& inMutex = control.getInMutex();
Condition& cond = control.getInCondition();
Thread incoming;
Incoming inTask;
int currId = -1;
static bool first = true;
// Init connection info
SocketAddress sock(info.address, info.internalPort);
ServerSocket server;
try {
server.bind(sock, true);
server.listen(5);
} catch(Exception& e) {
printKv("Could not initialize internal thread, please restart server ("<< e.displayText()<< ")");
}
StreamSocket client;
while(control.isLive()) {
inMutex.lock();
cond.wait(inMutex);
unsigned nextId = control.getConnectedId();
inMutex.unlock();
// NOTE: From a security perspective this is not safe.
// if someone tries to connect at the same time a rejoin
// was initiated, they could easily perform a MITM attack.
// However, since this is an academic exercise, I am not too
// concerned with security (as can be seen by many other components
// in this system as well).
if(currId != (int)nextId) {
currId = nextId;
// TODO: Update processing thread somehow
printKv("Told a new server should be connecting...");
try {
client = server.acceptConnection();
printKv("Incoming server connected: "<< currId);
inTask.cancel();
if(!first)
incoming.join();
first = false;
inTask = Incoming(client, &config.getThreadControl());
incoming.start(inTask);
printKv("Handling new server");
} catch(TimeoutException& e) {
printKv("Server did not connect in time - we don't want the system to be hung up, though ("<< e.displayText() <<")");
}
}
}
server.close();
}
示例13: testConnect
void SocketTest::testConnect()
{
ServerSocket serv;
serv.bind(SocketAddress());
serv.listen();
StreamSocket ss;
Timespan timeout(250000);
ss.connect(SocketAddress("localhost", serv.address().port()), timeout);
}
示例14: _main
static int _main(int argc, char **argv) {
vector<string> args(argc-1);
for (int i=1; i<argc; ++i) {
args[i-1] = argv[i];
}
args.at(0);
//YaoProtocol yao;
Socket *s;
ifstream fmtin("/home/louis/sfe/priveq.fmt");
FmtFile fmt = FmtFile::parseFmt(fmtin);
cout << "Read fmt file" << endl;
ifstream in("/home/louis/sfe/priveq.circ");
Circuit_p cc = Circuit::parseCirc(in);
if (args[0] == ("A")) {
args.at(1);
BigInt n = BigInt::parseString(args[1]);
bit_vector input_bits = toBits(n, fmt.numInputs(0));
cout << "connecting" << endl;
s = new Socket("localhost", 5437);
DataOutput *out = s->getOutput();
DataInput *in = s->getInput();
YaoSender cli;
cli.setStreams(in, out);
cli.go(cc, fmt, input_bits);
delete out;
delete in;
delete s;
} else if (args[0] == ("B")) {
args.at(1);
BigInt n = BigInt::parseString(args[1]);
bit_vector input_bits = toBits(n, fmt.numInputs(1));
args.at(1);
YaoChooser srv;
cout << "listening" << endl;
ServerSocket *ss = new ServerSocket(5437);
s = ss->accept();
DataOutput *out = s->getOutput();
DataInput *in = s->getInput();
srv.setStreams(in, out);
bit_vector circ_out = srv.go(cc, fmt, input_bits);
for (uint i=0; i<circ_out.size(); ++i) {
cout << "output " << i << ": " << circ_out[i] << endl;
}
delete s;
delete ss;
delete out;
delete in;
}
return 0;
}
示例15: run
virtual void run(){
try{
unsigned char buf[1000];
ServerSocket server;
server.bind( "127.0.0.1", SocketFactoryTest::DEFAULT_PORT );
net::Socket* socket = server.accept();
server.close();
socket->setSoLinger( false, 0 );
synchronized(&mutex)
{
numClients++;
mutex.notifyAll();
}
while( !done && socket != NULL ){
io::InputStream* stream = socket->getInputStream();
memset( buf, 0, 1000 );
try{
if( stream->read( buf, 1000, 0, 1000 ) == -1 ) {
done = true;
continue;
}
lastMessage = (char*)buf;
if( strcmp( (char*)buf, "reply" ) == 0 ){
io::OutputStream* output = socket->getOutputStream();
output->write( (unsigned char*)"hello", (int)strlen("hello"), 0, (int)strlen("hello") );
}
}catch( io::IOException& ex ){
done = true;
}
}
socket->close();
delete socket;
numClients--;
synchronized(&mutex) {
mutex.notifyAll();
}
}catch( io::IOException& ex ){
printf("%s\n", ex.getMessage().c_str() );
CPPUNIT_ASSERT( false );
}catch( ... ){
CPPUNIT_ASSERT( false );
}
}