Exemple #1
0
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();
}
//-------------------------------------------------------------------------------------------------------------------
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() ;
}
//----< 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"]);
}
Exemple #4
0
    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;
    }
  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;
  }
Exemple #6
0
/**
 * Generates a simulation result message containing all variables and parameters from the filter mask
 * and sends the string to a server via message parsing and tcp/ip
 */
int sendMessageToClientGUI(long nStates, long nAlgebraic, long nParameters) {

  bool retValue = true;

  string resultMessage = createResultMessageWithNames(nStates, nAlgebraic, nParameters);

  if (debugTransfer)
  {
         cout << resultMessage << endl; fflush(stdout);
  }

  /*
   * Sends the simulation result data string to a server
   */
  transfer_client_socket.send(resultMessage);

  return retValue;
}
Exemple #7
0
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;
}
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;
}
Exemple #9
0
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();
}
Exemple #10
0
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));
}
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();
}
//----< 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;
}
Exemple #13
0
//-------------------------------------------------------------------------------------------------------------------
TEST_F(SocketTest, UnixConnect)
{
	Socket skts ;
	Socket sktc ;

	// client
	EXPECT_FALSE(sktc.clientConnect(UNIX_SKTNAME)) ;

	// server
	EXPECT_TRUE(skts.serverListen(UNIX_SKTNAME)) ;

	// client
	EXPECT_TRUE(sktc.clientConnect(UNIX_SKTNAME)) ;

	sktc.close() ;
	skts.close() ;
}
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;
}
//----< 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;
		}
	}
}
Exemple #16
0
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;
}
Exemple #17
0
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;
}
Exemple #18
0
//-------------------------------------------------------------------------------------------------------------------
TEST_F(SocketTest, TcpConnect)
{
	Socket skts ;
	Socket sktc ;

	// client
	EXPECT_FALSE(sktc.clientConnect(TCP_SKTNAME)) ;

	// server
//	EXPECT_TRUE(skts.serverListen("*:3333")) ;
	EXPECT_TRUE(skts.serverListen(TCP_SKTNAME)) ;

	// client
	EXPECT_TRUE(sktc.clientConnect(TCP_SKTNAME)) ;

	sktc.close() ;
	skts.close() ;
}
Exemple #19
0
AsynchIO::AsynchIO(const Socket& s,
                   ReadCallback rCb, EofCallback eofCb, DisconnectCallback disCb,
                   ClosedCallback cCb, BuffersEmptyCallback eCb, IdleCallback iCb) :

    DispatchHandle(s, 
                   boost::bind(&AsynchIO::readable, this, _1),
                   boost::bind(&AsynchIO::writeable, this, _1),
                   boost::bind(&AsynchIO::disconnected, this, _1)),
    readCallback(rCb),
    eofCallback(eofCb),
    disCallback(disCb),
    closedCallback(cCb),
    emptyCallback(eCb),
    idleCallback(iCb),
    socket(s),
    queuedClose(false),
    writePending(false) {

    s.setNonblocking();
}
Exemple #20
0
//------------------------------------------------------------------------------
int netserver_open(lua_State *L)
{
    if (!luaT_check(L, 2, LUA_TNUMBER, LUA_TTABLE))
        return luaT_error(L, "netserver: listen [incorrect parameters]");
    if (!_network.init())
        return luaT_error(L, "netserver: listen [network not initialized]");
    int port = lua_tointeger(L, 1);
    if (port < 0 || port > 65535)
        return luaT_errorf(L, "netserver: listen [incorrect (%d) port number]", port);

    for (int i=0,e=listen_sockets.size(); i<e; ++i) 
    {
        ListenSocket *s = listen_sockets[i];
        if (s->port == port) 
            return luaT_errorf(L, "netserver: listen [port (%d) busy]", port);
    }

    ListenSocket *new_socket = NULL;
    Socket s;
    if (s.create())
    {
       if (s.setreuseopt() &&
           s.bind(port) &&
           s.setnonblockopt() &&
           s.listen(10))
       {
           new_socket = new (std::nothrow) ListenSocket();
           if (new_socket)
           {
               new_socket->socket = s;
               new_socket->port = port;
               listen_sockets.push_back(new_socket);
               selector.AddSocket(s);
           }
       }
       if (!new_socket)
           s.close();
    }
    if (!new_socket)
        return luaT_errorf(L, "netserver: listen [port (%d) does't opened]", port);
    
    lua_pushboolean(L, 1);
    return 1;
}
Exemple #21
0
void SecondoServer::CallGetOperatorIndexes(){

   string name;
   ListExpr args;
   iostream& iosock = client->GetSocketStream();
   getline(iosock,name);
   AlgebraManager* am = SecondoSystem::GetAlgebraManager();
   //NestedList* nl = am->getListStorage();
   NestedList* nl1 = SecondoSystem::GetNestedList(); 

   nl1->ReadBinaryFrom(iosock, args);

   string cmdEnd;
   getline(iosock, cmdEnd);
   if(cmdEnd=="</REQUESTOPERATORINDEXES>"){
       iosock << "<OPERATORINDEXESRESPONSE>" << endl;
       int algId;
       int OpId;
       int funId;
       ListExpr resList;
    
       NList::setNLRef(nl1); 
       bool ok = am->findOperator(name,args,resList, algId, OpId,funId);
       NList::setNLRef(nl);
      
       stringstream ss;
       ss << (ok?"1":"0") << endl;
       ss << algId << endl << OpId << endl << funId << endl;
       iosock << ss.str();
       nl1->WriteBinaryTo(resList, iosock);
       iosock << endl;
       iosock << "</OPERATORINDEXESRESPONSE>" << endl;
   } else {
     
    iosock << "<SecondoError>" << endl
           << "SECONDO-0080 Protocol error: "
           << "</REQUESTOPERATORINDEXES> expected." << endl
           << " received '" << cmdEnd << "'" << endl
           << "</SecondoError>" << endl;
   }
}
Exemple #22
0
 static uint threadProc(void* data)
 {
   ThreadProc* threadData = (ThreadProc*)data;
   Socket socket;
   ASSERT(socket.open());
   ASSERT(socket.connect(Socket::loopbackAddr, 7266));
   Thread::sleep(42);
   threadData->sent = true;
   ASSERT(socket.send(threadData->testData, sizeof(threadData->testData)) == sizeof(threadData->testData));
   byte receiveData[100];
   ASSERT(socket.recv(receiveData, sizeof(receiveData)) == sizeof(receiveData));
   ASSERT(Memory::compare(&receiveData, &threadData->testData, sizeof(receiveData)) == 0);
   socket.close();
   return 32;
 }
// -------------- << Sends Files + Dependencies via socket >> -----------------
bool Sender::sendFilesWithDeps(const std::string & fileToSend, Socket & socket, std::vector<std::string> dependencies, int fPort, int tport)
{
	std::string fqname = fileToSend;
	FileSystem::FileInfo fi(fqname);
	size_t fileSize = fi.size();
	std::string sizeString = Converter<size_t>::toString(fileSize);
	std::string toPort = Converter<int>::toString(tport);
	std::string fromPort = Converter<int>::toString(fPort);
	std::string noOfDeps = Converter<size_t>::toString(dependencies.size());
	FileSystem::File file(fqname);
	file.open(FileSystem::File::in, FileSystem::File::binary);
	if (!file.isGood())
		return false;
	HttpMessage msg = makeMessage(1, "", "localhost::"+toPort);
	msg.addAttribute(HttpMessage::Attribute("file", fileToSend));
	msg.addAttribute(HttpMessage::Attribute("content-length", sizeString));
	msg.addAttribute(HttpMessage::Attribute("Dep-Count", noOfDeps));
	msg.addAttribute(HttpMessage::Attribute("To-Port", toPort));
	msg.addAttribute(HttpMessage::Attribute("From-Port", fromPort));
	for (size_t i = 0; i < dependencies.size(); i++)
	{
		std::string iter = Converter<size_t>::toString(i);
		msg.addAttribute(HttpMessage::Attribute("dep"+iter, dependencies[i]));
	}	
	sendMessage(msg, socket);
	const size_t BlockSize = 2048;
	Socket::byte buffer[BlockSize];
	while (true)
	{
		FileSystem::Block blk = file.getBlock(BlockSize);
		if (blk.size() == 0)
			break;
		for (size_t i = 0; i < blk.size(); ++i)
			buffer[i] = blk[i];
		socket.send(blk.size(), buffer);
		if (!file.isGood())
			break;
	}
	file.close();
	return true;
}
Exemple #24
0
void ApplicationOctetStreamPart::Send (Socket & socket) const
{
    socket.SendLine ("Content-Type: application/octet-stream;");
    socket.SendLine ("\tname=\"" + _filename + "\"");
    socket.SendLine ("Content-Transfer-Encoding: base64");
    socket.SendLine ("Content-Disposition: attachment;");
    socket.SendLine ("\tfilename=\"" + _filename + "\"");
    socket.SendLine ();

    MemFileReadOnly srcFile (_attPath.ToString ());
    Smtp::Output output (socket);
    Base64::Encode (srcFile.GetBuf (), srcFile.GetBufSize (), output);

    socket.SendLine ();
}
Exemple #25
0
	iptsocks_connection(Poll& p, HANDLE h1) :
			p(p), s1(h1, AF_INET, SOCK_STREAM, 0), s2(AF_INET, SOCK_STREAM, 0), incremented(false) {
		try {
			j.from1to2= {&iptsocks_connection::from1to2,this};
			j.from2to1= {&iptsocks_connection::from2to1,this};
			j.s1 = &s1;
			j.s2 = &s2;
			p.add(s1);
			p.add(s2);
			sockaddr_in dstaddr;
			socklen_t dstlen = sizeof(dstaddr);
			if (getsockopt(h1, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr *) &dstaddr, &dstlen) != 0) throw runtime_error(
					strerror(errno));
			ep.setSockAddr((sockaddr*) &dstaddr);
			//IPEndPoint ep2(IPAddress(iptsocks_params.socks_host), iptsocks_params.socks_port);
			s2.connect(*socks_host_ep, Callback(&iptsocks_connection::cb_connect, this));
			retain();
		} catch (exception& ex) {

		}
	}
  void async_accept(implementation_type& impl, Socket& peer,
      endpoint_type* peer_endpoint, Handler& handler)
  {
    // Allocate and construct an operation to wrap the handler.
    typedef win_iocp_socket_accept_op<Socket, protocol_type, Handler> op;
    typename op::ptr p = { asio::detail::addressof(handler),
      op::ptr::allocate(handler), 0 };
    bool enable_connection_aborted =
      (impl.state_ & socket_ops::enable_connection_aborted) != 0;
    p.p = new (p.v) op(*this, impl.socket_, peer, impl.protocol_,
        peer_endpoint, enable_connection_aborted, handler);

    ASIO_HANDLER_CREATION((io_context_, *p.p, "socket",
          &impl, impl.socket_, "async_accept"));

    start_accept_op(impl, peer.is_open(), p.p->new_socket(),
        impl.protocol_.family(), impl.protocol_.type(),
        impl.protocol_.protocol(), p.p->output_buffer(),
        p.p->address_length(), p.p);
    p.v = p.p = 0;
  }
Exemple #27
0
void
SecondoServer::WriteResponse( const int errorCode, const int errorPos,
                              const string& errorMessage, ListExpr resultList )
{
  ListExpr msg = nl->TextAtom();
  nl->AppendText( msg, errorMessage );
  
  ListExpr list = nl->FourElemList(
                    nl->IntAtom( errorCode ),
                    nl->IntAtom( errorPos ),
                    msg,
                    resultList );

  iostream& iosock = client->GetSocketStream();
 
  csp->IgnoreMsg(true); 
  iosock << "<SecondoResponse>" << endl;
  csp::sendList(iosock, NList(list));  
  iosock << "</SecondoResponse>" << endl;
  
}
Exemple #28
0
bool HttpRequest::readLine(string &s)
{
    for (;;){
        char c;
        int n = m_sock->read(&c, 1);
        if (n < 0){
            error_state(ErrorProxyConnect);
            return false;
        }
        if (n == 0) return false;
        bIn << c;
        if (c == '\n') break;
    }
    s = "";
    for (; bIn.readPos() < bIn.writePos(); ){
        char c;
        bIn.unpack(&c, 1);
        if ((c == '\r') || (c == '\n')) continue;
        s += c;
    }
    return true;
}
Exemple #29
0
void thread(void* arg)
{
  stringstream stream;
  while(true)
  {
    if(sock.isBound)
    {
      if(sock.recvMessage(&fromAddr, messageBuffer) < 0)
      {
        exit(WSAGetLastError());
      }
    }
    if(!memcmp(messageBuffer, CIM, 3))
      {
        stream.str(string());
        stream << messageBuffer + 3;
        conversation.push_back(stream.str());
      }
      memset(messageBuffer, '\0', MESSAGE_MAX);
  }
  _endthread();
}
Exemple #30
0
void MsgClient::downloadFile(const std::string& fqname, size_t fileSize, Socket& socket) {
	std::string path = "Download/" + fqname;
	FileSystem::File file(path);
	file.open(FileSystem::File::out, FileSystem::File::binary);
	if (!file.isGood())
	{
		/*
		* This error handling is incomplete.  The client will continue
		* to send bytes, but if the file can't be opened, then the server
		* doesn't gracefully collect and dump them as it should.  That's
		* an exercise left for students.
		*/
		Show::write("\n\n  can't open file " + fqname);
	}

	const size_t BlockSize = 2048;
	Socket::byte buffer[BlockSize];

	size_t bytesToRead;
	while (true)
	{
		if (fileSize > BlockSize)
			bytesToRead = BlockSize;
		else
			bytesToRead = fileSize;

		socket.recv(bytesToRead, buffer);

		FileSystem::Block blk;
		for (size_t i = 0; i < bytesToRead; ++i)
			blk.push_back(buffer[i]);

		file.putBlock(blk);
		if (fileSize < BlockSize)
			break;
		fileSize -= BlockSize;
	}
	file.close();
}