⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chttpsocketengine.cpp

📁 Symbian手机上一个简单的http server 服务器代码
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/**
 * CHttpSocketEngine implementation
 *
 * This file is part of HttpServer.
 *
 * HttpServer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * HttpServer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HttpServer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "HttpServer.h"

// Debug messages
_LIT(KConnectingToSocketServer, "Connecting to SocketServ");
_LIT(KCreatingSocket, "Creating socket");
_LIT(KBindingPort, "Binding to port 80");
_LIT(KStartingToListen, "Starting to listen");
_LIT(KAcceptingConnections, "Accepting connections");
_LIT(KAcceptError, "Accept error (timeout?)");
_LIT(KClientConnected, "Client connected");
_LIT(KClientDisconnected, "Client disconnected");
_LIT(KNotListening, "Listening stopped");
_LIT(KCannotConnectSocketServ, "Cannot connect socket server");
_LIT(KCannotOpenSocket, "Cannot open socket");
_LIT(KCannotBindSocket, "Cannot bind socket");
_LIT(KCannotListenSocket, "Cannot listen socket");
_LIT(KCannotOpenClientSocket, "Cannot open client socket");
_LIT(KCannotStartDocument, "Cannot start document");
_LIT(KReadingChunkFormat, "Reading chunk %d");
_LIT(KCancelledFormat, "Cancelled file (%d/%d)");
_LIT(KDownloadReadyFormat, "Download ready (%d/%d)");
_LIT(KReceivingChunkedFormat, "Receiving chunked (%d)");
_LIT(KReceivingStraightFormat, "Receiving straight (%d)");
_LIT(KTransferEncodingChunked, "Transfer-Encoding: chunked");

// HTTP literals
_LIT8(KTransferEncoding, "Transfer-Encoding:");
_LIT8(KChunked, "chunked");
_LIT8(KContentLength, "Content-Length:");
_LIT8(KBluetoothBridge, "btbridge");

// Known URLs
_LIT8(KBtBridge, "/btbridge");

// HTTP responses
_LIT8(K200ResponseFormat, "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n");
_LIT8(K400BadRequest, "HTTP/1.0 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: 17\r\n\r\n400 Bad Request\r\n");
_LIT8(K404NotFound, "HTTP/1.0 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\n404 Not Found\r\n");

const TUid KPhoneUidWmlBrowser = { 0x10008D39 };

CHttpSocketEngine::CHttpSocketEngine(TInt aPriority): CActive(aPriority)
{
	appui = NULL;
	view = NULL;
	listening = EFalse;
}

void CHttpSocketEngine::ConstructL(CHttpAppUi *nappui)
{
	appui = nappui;
	view = appui->View();
	CActiveScheduler::Add(this);
}

CHttpSocketEngine::~CHttpSocketEngine()
{
	if (listening)
	{
		StopListeningL();
	}
}

TBool CHttpSocketEngine::ToggleListeningL()
{
	if (!listening)
	{
		StartListeningL();
	}
	else
	{
		StopListeningL();
	}
	
	return listening;
}

TBool CHttpSocketEngine::IsListening()
{
	return listening;
}

void CHttpSocketEngine::StartListeningL(TBool nomsg)
{
	TInt err;
	
	// view->PrintL(KConnectingToSocketServer);
	err = iSocketServ.Connect();
	if (err != KErrNone)
	{
		view->PrintL(KCannotConnectSocketServ);
		return;
	}
	
	// view->PrintL(KCreatingSocket);
	if ((err = iServerSocket.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp)) != KErrNone)
	{
		iSocketServ.Close();
		view->PrintL(KCannotOpenSocket);
		return;
	}
	
	// view->PrintL(KBindingPort);
	if ((err = iServerSocket.SetLocalPort(80)) != KErrNone)
	{
		iServerSocket.Close();
		iSocketServ.Close();
		view->PrintL(KCannotBindSocket);
		return;
	}
	
	// view->PrintL(KStartingToListen);
	if ((err = iServerSocket.Listen(10)) != KErrNone)
	{
		iServerSocket.Close();
		iSocketServ.Close();
		view->PrintL(KCannotListenSocket);
		return;
	}
	
	// view->PrintL(KCreatingSocket);
	if (iClientSocket.Open(iSocketServ) != KErrNone)
	{
		view->PrintL(KCannotOpenClientSocket);
		iServerSocket.Close();
		iSocketServ.Close();
		return;
	}
	
	if (!nomsg) view->PrintL(KAcceptingConnections);
	
	iServerSocket.Accept(iClientSocket, iStatus);
	SetActive();
	
	listening = ETrue;
}

void CHttpSocketEngine::StopListeningL()
{
	Cancel();
}

/**
 * This method gets called when we cancel the active object
 * by calling Cancel() from StopListeningL().
 */

void CHttpSocketEngine::DoCancel()
{
	iServerSocket.CancelAll();
	iServerSocket.Close();
	iSocketServ.Close();
	listening = EFalse;
	view->PrintL(KNotListening);
}

/**
 * This method gets called when an Accept() request has completed
 * and there is a client connection to be served. We do some error
 * checking, handle the connection and then Accept() again.
 */

void CHttpSocketEngine::RunL()
{
	if (iStatus != KErrNone)
	{
		// Listener failure. This happens after some timeout.
		// We'll just set up the listener again.
		iClientSocket.Close();
		iServerSocket.Close();
		listening = EFalse;
		StartListeningL(EFalse);
		return;
	}
	
	HandleClientL(iClientSocket);
	iClientSocket.Close();
	
	if (iClientSocket.Open(iSocketServ) != KErrNone)
	{
		view->PrintL(KCannotOpenClientSocket);
		iServerSocket.Close();
		iSocketServ.Close();
		listening = EFalse;
		return;
	}
	
	iServerSocket.Accept(iClientSocket, iStatus);
	SetActive();
}

TInt CHttpSocketEngine::ReadChunkSize(RSocket &client)
{
	TInt chunksize = 0;
	TInt i;
	
	if (ReadLine(client, buf))
	{
		for (i = 0; i < buf.Length(); i++)
		{
			if (buf[i] == ';') break;
			if ('0' <= buf[i] && buf[i] <= '9') chunksize = (chunksize * 16) + (buf[i]-'0');
			else if ('a' <= buf[i] && buf[i] <= 'z') chunksize = (chunksize * 16) + (buf[i]-'a'+10);
			else if ('Z' <= buf[i] && buf[i] <= 'Z') chunksize = (chunksize * 16) + (buf[i]-'A'+10);
		}
	}
	
	return chunksize;
}

TInt CHttpSocketEngine::ReadChunk(RSocket &client, TInt chunksize, TDes8 &buf)
{
	/// XXX TODO
	return 0;
}

TInt CHttpSocketEngine::ReadBuffer(RSocket &client, TDes8 &buf)
{
	TInt chunk;
	int len = buf.MaxLength();
	TRequestStatus status;
	TSockXfrLength slen;
	
	buf.SetLength(0);
	
	while (ETrue)
	{
		// Copy as much data from linebuf as possible.
		chunk = linebuf.Length();
		if (chunk > len) chunk = len;
		readbuf.Copy(linebuf);
		readbuf.SetLength(chunk);
		buf.Append(readbuf);
		len -= chunk;
		linebuf.Delete(0, chunk);
		
		// Check if we're satisfied.
		if (buf.Length() > 0)
		{
			return buf.Length();
		}
		
		// We need to read more data from the network.
		
		linebuf.SetLength(0);
		client.RecvOneOrMore(readbuf, 0, status, slen);
		User::WaitForRequest(status);
		if (status != KErrNone || readbuf.Length() <= 0)
		{
			// Read failed. Return what we got.
			return buf.Length();
		}
		
		// Buffer the data that we read.
		linebuf.Copy(readbuf);
	}
}

TBool CHttpSocketEngine::ReadLine(RSocket &client, TDes8 &buf)
{
	TInt pos;
	TInt chunk;
	TSockXfrLength len;
	TRequestStatus status;
	
	while (ETrue)
	{
		// Check if linebuf contains a newline.
		
		pos = linebuf.Locate('\n');
		if (pos != KErrNotFound)
		{
			// Found a newline. Split linebuf and copy data to buf.
			buf.Copy(linebuf);
			buf.SetLength(pos);
			if (buf[buf.Length()-1] == '\r') buf.SetLength(buf.Length()-1);
			// Keep remaining data in linebuf.
			linebuf.Delete(0, pos+1);
			return ETrue;
		}
		
		// Read more data until we get a newline, an error, or an overflow.
		
		client.RecvOneOrMore(readbuf, 0, status, len);
		User::WaitForRequest(status);
		if (status != KErrNone)
		{
			// Read failed. Return remaining buf.
			buf.Copy(linebuf);
			linebuf.SetLength(0);
			return ETrue;
		}
		
		// Read OK, got at least one byte. Check for overflow.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -