?? cometclient.cs
字號:
/** Copyright (c) 2006, All-In-One Creations, Ltd.* All rights reserved.* * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:* * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.* * Neither the name of All-In-One Creations, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.**//** * Project: emergetk: stateful web framework for the masses * File name: CometClient.cs * Description: Once the CometServer accepts a socket, the socket is wrapped up in a CometClient instance, which is then bound * to the relevant context. Should probably be renamed to CometSocket, and CometSocket should be renamed CometClient (or maybe CometWidget)! * * Author: Ben Joldersma * */using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.IO;using System.Runtime.InteropServices;namespace EmergeTk{ public class CometClient : Surface { string method, url; Dictionary<string, string> headers = new Dictionary<string, string>(), cookies = new Dictionary<string,string>(); Socket s; Context context; ICometWriter writer; public CometClient(Socket s) { this.s = s; } public bool Connected { get { return s.Connected; } } public string CacheKey { get { return url; } } public Context Context { get { return context; } set { context = value; } } public Dictionary<string, string> Headers { get { return headers; } } public Dictionary<string, string> Cookies { get { return cookies; } } protected NetworkStream ns; protected BufferedStream bs; protected StreamReader sr; protected StreamWriter sw; public void Setup() { try { ns = new NetworkStream(s, FileAccess.ReadWrite); bs = new BufferedStream(ns); sr = new StreamReader(ns); sw = new StreamWriter(bs); parseRequest(); readHeaders(); string sessionId; if( Cookies.ContainsKey("ASP.NET_SessionId") ) { sessionId = Cookies["ASP.NET_SessionId"]; } else if( Cookies.ContainsKey("ASPSESSION") ) { sessionId = Cookies["ASPSESSION"]; } else { throw new Exception("Could not find session key."); } Context context = Context.GetContext(sessionId, CacheKey); if (context != null) { System.Console.WriteLine("found context"); this.Context = context; writer.Context = context; context.ConnectComet(this); } else { System.Console.WriteLine("failed to find context."); Write("alert('Comet lost context.');"); Shutdown(); } writeSuccess(); } catch(Exception e) { System.Console.WriteLine("error in CometClient.Setup: " + e.Message); } } public void Shutdown() { ns.Close(); s.Close(); if (Context != null) { Context.DisconnectComet(); } } public void parseRequest() { String request = sr.ReadLine(); string[] tokens = request.Split(new char[] { ' ' }); method = tokens[0]; if (method == "FLASH") { writer = new FlashCometWriter(sw,ns); StateObject so = new StateObject(); so.workSocket = s; s.BeginReceive(so.buffer,0,so.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), so); } else { writer = new HtmlCometWriter(sw); } url = tokens[1].Substring(1); } string lastInput; int sameCount = 0; public void Receive(IAsyncResult ar) { StateObject so = ar.AsyncState as StateObject; if (!so.workSocket.Connected) { return; } try { int length; for (length = 0; length < so.buffer.Length; length++) { if (so.buffer[length] == 0) break; } string input = new string(Encoding.ASCII.GetChars(so.buffer, 0, length)); if (input == lastInput) { sameCount++; } else { sameCount = 0; lastInput = input; } so.workSocket.EndReceive(ar); if (input.StartsWith("CLOSE::") || !so.workSocket.Connected || sameCount > 10 ) { context.Unregister(); Shutdown(); return; } so.buffer.Initialize(); so.workSocket.BeginReceive(so.buffer, 0, so.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), so); context.HandleEvents("RECV", input); } catch { if (!so.workSocket.Connected) { if (context != null) context.Unregister(); } } } public void readHeaders() { try { String line; while ((line = sr.ReadLine()) != null && line != "") { //System.Console.WriteLine("header: " + line); string[] tokens = line.Split(new char[] { ':' }); String name = tokens[0].Trim(); String value = ""; for (int i = 1; i < tokens.Length; i++) { value += tokens[i].Trim(); if (i < tokens.Length - 1) tokens[i] += ":"; } headers[name] = value; //System.Console.WriteLine(string.Format("header {0} : {1}", name, value)); if (name == "Cookie") { string[] cookieTokens = value.Split(new char[] { '=', ';' },StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < cookieTokens.Length; i += 2) { cookies[cookieTokens[i].Trim()] = cookieTokens[i + 1].Trim(); } } } } catch( Exception e ) { System.Console.WriteLine("error reading headers: " + e.Message); } } public virtual void writeSuccess() { writer.WriteSuccess(); } public override void Write(string data) { try { writer.Write(data); } catch (Exception e) { if (Context != null) { Shutdown(); } throw e; } } // State object for reading client data asynchronously public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -