您的位置:首页 > 编程语言 > C语言/C++

websocket c++ example

2013-12-24 17:43 351 查看
//============================================================================
// Name        : websocket.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

#include <Poco/Net/WebSocket.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/ServerSocket.h>
#include <Poco/Net/NetException.h>
#include <Poco/Exception.h>

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::WebSocket;
using Poco::Net::WebSocketException;
using Poco::Exception;

using namespace std;

int ws_main() {
char buffer[1024];
int flags;
int n;
std::string payload;

try {
HTTPClientSession cs("echo.websocket.org", 80);
HTTPRequest request(HTTPRequest::HTTP_GET, "/", "HTTP/1.1");
HTTPResponse response;
std::string cmd;

WebSocket * ws = new WebSocket(cs, request, response); // Causes the timeout

payload = "SGClient: Hello World!";
cout << "Send: SGClient: Hello World!" << endl;
ws->sendFrame(payload.data(), payload.size(), WebSocket::FRAME_TEXT);
n = ws->receiveFrame(buffer, sizeof(buffer), flags);
buffer
= '\0';
cout << "Received: " << buffer << endl;

while (cmd != "exit") {
cmd = "";
cout << "Please input[exit]:";
std::cin >> cmd;
ws->sendFrame(cmd.data(), cmd.size(), WebSocket::FRAME_TEXT);
n = ws->receiveFrame(buffer, sizeof(buffer), flags);
buffer
= '\0';
if (n > 0) {
std::cout << "Receive: " << buffer << std::endl;
}
}

ws->shutdown();
} catch (Exception ex) {
cout << ex.displayText() << endl;
cout << ex.what() << endl;
return -1;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: