本文整理汇总了C++中Socket类的典型用法代码示例。如果您正苦于以下问题:C++ Socket类的具体用法?C++ Socket怎么用?C++ Socket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Socket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: recvSingleFrom
std::string Grid::recvSingleFrom(Socket& sock) {
ByteArray x, y, value, gameOver;
for (int i = 0; i < 2; i++) {
sock.Read(x);
sock.Write(ByteArray("RECEIVED"));
sock.Read(y);
sock.Write(ByteArray("RECEIVED"));
sock.Read(value);
sock.Write(ByteArray("RECEIVED"));
this->_grid[atoi(x.ToString().c_str())][atoi(y.ToString().c_str())] = value.ToString()[0];
}
sock.Read(gameOver);
sock.Write(ByteArray("RECEIVED"));
return gameOver.ToString();
}
示例2: TEST_F
//-------------------------------------------------------------------------------------------------------------------
TEST_F(SocketTest, TcpPortRange)
{
Socket skts ;
Socket sktc ;
// server
EXPECT_TRUE(skts.serverListen("localhost:5555-6000")) ;
unsigned port(skts.getPort()) ;
EXPECT_EQ(5555u, port) ;
// client
EXPECT_TRUE(sktc.clientConnect("localhost:5555")) ;
std::cerr << "Accept..." << std::endl ;
std::shared_ptr<IComms> cfd(skts.accept()) ;
ASSERT_TRUE(cfd.get() != nullptr);
std::cerr << "Accepted" << std::endl ;
std::string message("Great, it works!") ;
std::string rx ;
// Client -> Server
std::cerr << "Sending..." << std::endl ;
bool ok ;
EXPECT_TRUE(ok=sktc.send(message));
if (!ok) ::perror("send") ;
std::cerr << "Sent" << std::endl ;
std::cerr << "Receiving..." << std::endl ;
EXPECT_TRUE(ok=cfd->receive(rx)) ;
if (!ok) ::perror("receive") ;
std::cerr << "Received" << std::endl ;
EXPECT_EQ(message, rx) ;
cfd->close() ;
sktc.close() ;
skts.close() ;
}
示例3: stringHandlingReply
//----< sending string handling reply to other peer >--------
void Sender::stringHandlingReply(Socket& si, Message& msg)
{
si.sendString("command:" + msg.getCommand());
map<string, string> att = msg.getAttributes();
si.sendString("sourceIP:" + att["sourceIP"]);
si.sendString("sourcePort:" + att["sourcePort"]);
si.sendString("destIP:" + att["destIP"]);
si.sendString("destPort:" + att["destPort"]);
si.sendString("body:" + att["body"]);
displayString("Peer(Client):" + att["sourcePort"] + " Sending String received acknowledgement to Peer(Server):" + att["destPort"]);
}
示例4: connect
bool
connect (Socket& s, std::string const& addr, int port)
{
try
{
typename Socket::endpoint_type ep (
boost::asio::ip::address::from_string (addr), port);
s.connect (ep);
pass();
return true;
}
catch (std::exception const& e)
{
fail (e.what());
}
return false;
}
示例5: async_accept
void async_accept(implementation_type& impl, Socket& peer,
endpoint_type* peer_endpoint, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_accept_op<Socket, Protocol, Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl.socket_, impl.state_, peer,
impl.protocol_, peer_endpoint, handler);
ASIO_HANDLER_CREATION((p.p, "socket", &impl, "async_accept"));
start_accept_op(impl, p.p, is_continuation, peer.is_open());
p.v = p.p = 0;
}
示例6: fetchNavdata
DroneController::FetchReturn DroneController::fetchNavdata()
{
ssize_t readLength = 0;
char data[sizeof(m_navdata)];
if((readLength = m_navdataSocket.recv(data, sizeof(data))) < 0 && errno != EAGAIN) {
perror("DroneController::fetchNavdata");
return DroneController::FetchError;
}
if(readLength < 0) return DroneController::NotFetched;
#ifdef ARDRONE_DEBUG
std::cout << "Read " << readLength << " bytes from navdata stream" << std::endl;
#endif
memcpy(m_navdata, data, sizeof(m_navdata));
return DroneController::Fetched;
}
示例7: isReady
bool SocketSelector::isReady(Socket& socket) const
{
SocketHandle handle = socket.getHandle();
if (handle != priv::SocketImpl::invalidSocket())
{
#if !defined(SFML_SYSTEM_WINDOWS)
if (handle >= FD_SETSIZE)
return false;
#endif
return FD_ISSET(handle, &m_impl->socketsReady) != 0;
}
return false;
}
示例8: main
int main(int argc, char** args){
if(argc != 2){
std::cerr << "Usage:client.exe ip" << std::endl;
exit(1);
}
Socket *s = NULL;
Thread *t = NULL;
try{
s = new Socket(PORT);
std::cout << "created socket" << s->getID() << std::endl;
char* addr = args[1];
addrinfo theirinfo = Socket::getTheirAddr(addr,PORT);
s->connectSocket(theirinfo);
std::cout << "Connected!" << std::endl;
char motd[Socket::MAX_MSG_LENGTH];
s->recvSocket(motd);
std::cout << "MOTD:" << motd << std::endl;
std::cout << "Type a message or " << EXIT_PHRASE << " to exit" << std::endl;
std::cout << "Type \\command to send a command" << std::endl;
t = new MessageReceivingThread(new ReceiveMessages(s));
t->start(); //TODO: check that is really started
char msg[Socket::MAX_MSG_LENGTH];
std::cin.getline(msg,Socket::MAX_MSG_LENGTH,'\n');
std::string strmsg = msg;
while(strmsg.compare(EXIT_PHRASE)!=0){
s->sendSocket(msg);
std::cin.getline(msg,Socket::MAX_MSG_LENGTH,'\n');
strmsg = msg;
}
}
catch(SocketException e){
std::cerr << e.what() << std::endl;
std::cerr << "Connection aborted." << std::endl;
}
if(s != NULL){
if(t != NULL)
t->terminate();
std::cout << "closed socket " << s->getID() << std::endl;
if(t != NULL)
delete(t);
delete(s);
}
WSACleanup();
}
示例9: _send
static Future<Nothing> _send(
Socket socket,
Owned<string> data,
size_t index,
size_t length)
{
// Increment the index into the data.
index += length;
// Check if we've sent all of the data.
if (index == data->size()) {
return Nothing();
}
// Keep sending!
return socket.send(data->data() + index, data->size() - index)
.then(lambda::bind(&_send, socket, data, index, lambda::_1));
}
示例10: ConnectOtherServer
SOCKET NetEngine::ConnectOtherServer(const char* ip, int port)
{
Socket sock;//监听socket
if ( !sock.Init( Socket::tcp ) ) return INVALID_SOCKET;
if ( !sock.Connect(ip, port) )
{
sock.Close();
return INVALID_SOCKET;
}
Socket::InitForIOCP(sock.GetSocket());
return sock.Detach();
}
示例11: readMessage
//----< this defines processing to frame messages >------------------
HttpMessage ClientHandler::readMessage(Socket& socket) {
connectionClosed_ = false;
HttpMessage msg;
while (true) { // read message attributes
std::string attribString = socket.recvString('\n');
if (attribString.size() > 1) {
HttpMessage::Attribute attrib = HttpMessage::parseAttribute(attribString);
msg.addAttribute(attrib);
}
else break;
}
if (msg.attributes().size() == 0) { // If client is done, connection breaks
connectionClosed_ = true; // and recvString returns empty string
return msg;
}
if (msg.attributes()[0].first == "POST") // read body if POST
{
if (msg.attributes()[0].second == "Message") msg = readBody(msg, socket); // case 0 - normal message
else if (msg.attributes()[0].second == "File") { // case 1 - client sending file to server
saveFileServer(msg, socket);
msg = constructMessage(msg);
}
else if (msg.attributes()[0].second == "closePackage") msg = closePackage(msg); // case 7 - close a package
else if (msg.attributes()[0].second == "returnFile") { // case 4 - server sends files to client
saveFileClient(msg, socket);
msg = constructMessage(msg);
}
}
else if (msg.attributes()[0].first == "GET") { // read message if GET
msg = readBody(msg, socket);
if (msg.attributes()[0].second == "getFileList") msg = getFileList(msg); // case 5 - request list of packages
else if (msg.attributes()[0].second == "getFileNameList") msg = getFileNameList(msg); // case 6 - request list of files in a packages
else if (msg.attributes()[0].second == "File" || msg.attributes()[0].second == "FileWithDeps")
msg = getFiles(msg, msg.attributes()[0].second);
}
else {
msg.removeAttribute("content-length");
std::string bodyString = "<msg>Error message</msg>";
std::string sizeString = Converter<size_t>::toString(bodyString.size());
msg.addAttribute(HttpMessage::Attribute("content-length", sizeString));
msg.addBody(bodyString);
}
return msg;
}
示例12: while
void* EpollMonitor::WaitAcceptEvent( void *pData )
{
#ifndef WIN32
epoll_event *events = new epoll_event[m_nMaxMonitor]; //epoll事件
Socket sock;
Socket sockClient;
SOCKET hSock;
/* 等待有事件发生 */
while ( !m_bStop )
{
int nPollCount = epoll_wait(m_hEPollAccept, events, m_nMaxMonitor, -1 );
if ( -1 == nPollCount ) break;
/* 处理所有事件,nfds 为返回发生事件数 */
int i = 0;
for ( i = 0; i < nPollCount; i++ )
{
if ( m_epollExit == events[i].data.fd )
{
::closesocket(m_epollExit);
break;
}
sock.Detach();
sock.Attach(events[i].data.fd);
while ( true )
{
sock.Accept( sockClient );
if ( INVALID_SOCKET == sockClient.GetSocket() ) break;
sockClient.SetSockMode();
hSock = sockClient.Detach();
AddMonitor(hSock);
while ( !m_acceptEvents->Push((void*)hSock) ) m_sigWaitAcceptSpace.Wait();
m_ioSignal.Notify();
}
}
}
delete[]events;
#endif
return NULL;
}
示例13: fileHandlingRequest
//----< sending file handling request to other peer >--------
void Sender::fileHandlingRequest(Socket& si, Message& msg)
{
map<string, string> att = msg.getAttributes();
displayString("command:" + msg.getCommand());
displayString("\nClient sending file located at->" + att["fileName"] + "\n\n");
if (!findFile(att["fileName"])){
Verbose::show("file Not Found!!", always);
return;
}
const size_t bufLen = 1024;
File::byte buffer[bufLen];
File bufferIn(att["fileName"]);
bufferIn.open(File::in, File::binary);
while (true)
{
int resultSize = bufferIn.getBuffer(bufLen, buffer);
att["contentLength"] = std::to_string(resultSize);
string temp1(buffer, resultSize);
if (resultSize < 1024)
{
for (int i = temp1.size(); i < 1024; i++)
buffer[i] = '#';
resultSize = 1024;
}
si.sendString("command:" + msg.getCommand());
si.sendString("sourceIP:" + att["sourceIP"]);
si.sendString("sourcePort:" + att["sourcePort"]);
si.sendString("destIP:" + att["destIP"]);
si.sendString("destPort:" + att["destPort"]);
si.sendString("fileName:" + att["fileName"]);
si.sendString("contentLength:" + att["contentLength"]);
si.sendString("\n");
si.send(resultSize, buffer);
displayString("Peer(Client):" + att["sourcePort"] + " Sending one buffer of " + Path::getName(att["fileName"], true) + " to other Peer(Server):" + att["destPort"]);
if (resultSize < bufLen || !bufferIn.isGood())
{
bufferIn.close();
displayString("----Client has sent whole " + Path::getName(att["fileName"], true) + " to server----");
break;
}
}
}
示例14: seconds
std::map<std::string, std::string> DroneController::configuration(const double timeout)
{
const double connectStart = seconds();
while(isNotTalking() && seconds() - connectStart < timeout) msleep(100);
if(isNotTalking()) return std::map<std::string, std::string>();
Socket s = Socket::tcp();
if(!s.setReusable(true)) return std::map<std::string, std::string>();
if(!s.connect(m_configAddress)) return std::map<std::string, std::string>();
if(!s.setBlocking(false)) return std::map<std::string, std::string>();
control(5);
control(4);
char buffer[65536];
buffer[0] = 0;
const double start = seconds();
ssize_t size = 0;
do {
size = s.recv(buffer, sizeof(buffer));
msleep(100);
} while(size < 0 && seconds() - start < timeout);
s.close();
if(size < 0) return std::map<std::string, std::string>();
// std::cout << buffer << std::endl;
std::map<std::string, std::string> ret;
// We convert all delimeters to '\0', then walk through with basic C
// string functions
for(size_t i = 0; i < size; ++i) {
if(buffer[i] == '\n') buffer[i] = 0;
if(buffer[i] == '=') buffer[i - 1] = 0;
}
const char *walker = buffer;
while(walker - buffer < size) {
const char *const key = walker;
const char *const value = walker + strlen(key) + 3;
if(strlen(key) >= 1 && strlen(value) >= 1) ret[key] = value;
walker = value + strlen(value) + 1;
}
return ret;
}
示例15: func
void* func(void* arg)
{
Socket clientsocket;
clientsocket.Init();
int ip = inet_addr("10.0.128.174");
int error = clientsocket.Connect(ip, htons(9090));
if (-1 == error)
{
printf("connect error:%d\n", errno);
return 0;
}
printf("connect succeed!\n");
char buf[MAXBUF];
memset(buf, 1, MAXBUF);
//sprintf(buf, "hello world!");
// while(scanf("%s", buf))
// {
clientsocket.SetSendBufLen(BUF);
clientsocket.SetRecvBufLen(0);
printf("send buf:%d\nrecv buf:%d\n", clientsocket.GetSendBufLen(), clientsocket.GetRecvBufLen());
//int n = 0;
while(1)
{
//int nsend = send(clientsocket.GetSocket(), buf, MAXBUF, 0);
scanf("%s", buf);
clientsocket.Send(buf, MAXBUF);
char tempbuf[MAXBUF];
//int nrecv = clientsocket.Recv(tempbuf, MAXBUF);
printf("recv:%s\n", tempbuf);
//printf("nsend:%d, n:\n", nsend, ++n);
memset(buf, 0, MAXBUF);
//usleep(1000);
//clientsocket.Close();
}
return 0;
}