public void Start() { Socket sock = Sockets.CreateTCPSocket("167.205.66.53", 2345); client = new ClientInfo(sock, false); // Don't start receiving yet client.MessageType = MessageType.CodeAndLength; client.OnReadMessage += new ConnectionReadMessage(ReadMessage); client.BeginReceive(); mcConnect = true; }
void ReadMessage(ClientInfo ci, uint code, byte[] buf, int len) { if (code == ClientInfo.ImageCodeUpper) { Console.WriteLine("Message length: " + len + ", code " + code.ToString("X8") + ", content:"); bu = new byte[len]; Array.Copy(buf, bu, len); //Console.WriteLine(" " + ByteBuilder.FormatParameter(new Parameter(ba, ParameterType.Byte))); updatedUpper = true; //OnImageRetrieved(EventArgs.Empty); } if (code == ClientInfo.ImageCodeLower) { Console.WriteLine("Message length: " + len + ", code " + code.ToString("X8") + ", content:"); bl = new byte[len]; Array.Copy(buf, bl, len); //Console.WriteLine(" " + ByteBuilder.FormatParameter(new Parameter(ba, ParameterType.Byte))); updatedLower = true; //OnImageRetrieved(EventArgs.Empty); } }
internal void ClientClosed(ClientInfo ci) { lock (SyncRoot) clients.Remove(ci.ID); }
internal ClientData(ClientInfo ci) { req.From = ((IPEndPoint)ci.Socket.RemoteEndPoint).Address; }
void SendResponse(ClientInfo ci, HttpRequest req, HttpResponse resp, bool close) { #if DEBUG Console.WriteLine("Response: "+resp.ReturnCode + Responses[resp.ReturnCode]); #endif ByteBuilder bb = new ByteBuilder(); bb.Add(Encoding.UTF8.GetBytes("HTTP/1.1 " + resp.ReturnCode + " " + Responses[resp.ReturnCode] + "\r\nDate: "+DateTime.Now.ToString("R")+ "\r\nServer: RedCoronaEmbedded/1.0"+ "\r\nConnection: "+(close ? "close" : "Keep-Alive"))); bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Encoding: " + (resp.Encoding == null ? "utf-8" : resp.Encoding))); if (resp.RawContent == null) bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.Content.Length)); else bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.RawContent.Length)); if(resp.ContentType != null) bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Type: "+resp.ContentType)); if(req.Session != null) bb.Add(Encoding.UTF8.GetBytes("\r\nSet-Cookie: _sessid="+req.Session.ID+"; path=/")); foreach(KeyValuePair<string, string> de in resp.Header) bb.Add(Encoding.UTF8.GetBytes("\r\n" + de.Key + ": " + de.Value)); bb.Add(Encoding.UTF8.GetBytes("\r\n\r\n")); // End of header if(resp.RawContent != null) bb.Add(resp.RawContent); else bb.Add(Encoding.UTF8.GetBytes(resp.Content)); ci.Send(bb.Read(0, bb.Length)); #if DEBUG Console.WriteLine("** SENDING\n"+resp.Content); #endif if(close) ci.Close(); }
void DoProcess(ClientInfo ci) { ClientData data = (ClientData)ci.Data; string sessid; if(data.req.Cookies.TryGetValue("_sessid", out sessid)) data.req.Session = (Session)sessions[sessid]; bool closed = Process(ci, data.req); data.state = closed ? ClientState.Closed : ClientState.Header; data.read = 0; HttpRequest oldreq = data.req; data.req = new HttpRequest(); // Once processed, the connection will be used for a new request data.req.Session = oldreq.Session; // ... but session is persisted data.req.From = ((IPEndPoint)ci.Socket.RemoteEndPoint).Address; }
bool ClientConnect(Server serv, ClientInfo new_client) { new_client.Delimiter = "\n"; new_client.OnRead += new ConnectionRead(ReadData); return true; // allow this connection }
bool ClientConnect(Server serv, ClientInfo new_client) { new_client.MessageType = MessageType.CodeAndLength; new_client.OnReadMessage += new ConnectionReadMessage(ReadMessage); return true; // allow this connection }
protected virtual bool Process(ClientInfo ci, HttpRequest req) { HttpResponse resp = new HttpResponse(); resp.Url = req.Url; for(int i = handlers.Count - 1; i >= 0; i--){ IHttpHandler handler = (IHttpHandler)handlers[i]; if(handler.Process(this, req, resp)){ SendResponse(ci, req, resp, resp.ReturnCode != 200); return resp.ReturnCode != 200; } } return true; }
static void ReadMessage(ClientInfo ci, uint code, byte[] buf, int len) { if (code == ClientInfo.CommandCode) { Console.WriteLine("Message length, code " + code.ToString("X8") + ", content:"+buf.ToString()); messageCommand(System.Text.Encoding.UTF8.GetString(buf, 0, len)); ci.SendMessage(ClientInfo.StringCode, Encoding.UTF8.GetBytes(code.ToString("X8")+" success")); } else if (code == ClientInfo.VoiceCode) { Console.WriteLine("Message length, code " + code.ToString("X8") + ", content:" + buf.ToString()); messageVoice(System.Text.Encoding.UTF8.GetString(buf, 0, len)); ci.SendMessage(ClientInfo.VoiceCode, Encoding.UTF8.GetBytes(code.ToString("X8") + " success")); } else if (code == ClientInfo.moveToCode) { Console.WriteLine("Message length, code " + code.ToString("X8") + ", content:" + buf.ToString()); string[] value = System.Text.Encoding.UTF8.GetString(buf, 0, len).Split(','); naoMotion.moveTo(float.Parse(value[0]), float.Parse(value[1]), float.Parse(value[2])); ci.SendMessage(ClientInfo.VoiceCode, Encoding.UTF8.GetBytes(code.ToString("X8") + " success")); } else if (code == ClientInfo.movePeonCode) { Console.WriteLine("Message length, code " + code.ToString("X8") + ", content:" + buf.ToString()); string[] value = System.Text.Encoding.UTF8.GetString(buf, 0, len).Split(','); naoMotion.movePeon(float.Parse(value[0]), float.Parse(value[1]), float.Parse(value[2]), float.Parse(value[3]), float.Parse(value[4]), float.Parse(value[5])); ci.SendMessage(ClientInfo.movePeonCode, Encoding.UTF8.GetBytes(code.ToString("X8") + " success")); } }
void ReadData(ClientInfo ci, uint code, byte[] bytes, int len) { Console.WriteLine("Received " + len + " bytes: " + System.Text.Encoding.UTF8.GetString(bytes, 0, len)); }
public void Start() { Socket sock = Sockets.CreateTCPSocket("localhost", 2345); client = new ClientInfo(sock, false); // Don't start receiving yet client.MessageType = MessageType.Length; client.OnReadMessage += new ConnectionReadMessage(ReadData); client.BeginReceive(); }
void ReadData(ClientInfo ci, String text) { Console.WriteLine("Received text message: " + text); }
void Start() { Socket sock = Sockets.CreateTCPSocket("localhost", 2345); client = new ClientInfo(sock, false); // Don't start receiving yet client.OnRead += new ConnectionRead(ReadData); client.Delimiter = "\n"; // this is the default, shown for illustration client.BeginReceive(); }
void Start() { Socket sock = Sockets.CreateTCPSocket("localhost", 2345); client = new ClientInfo(sock, false); // Don't start receiving yet client.OnReadBytes += new ConnectionReadBytes(ReadData); client.BeginReceive(); }
// ASYNC CALLBACK CODE void AcceptCallback(IAsyncResult ar) { try { Socket server = (Socket)ar.AsyncState; Socket cs = server.EndAccept(ar); // Start the thing listening again server.BeginAccept(new AsyncCallback(AcceptCallback), server); ClientInfo c = new ClientInfo(cs, null, null, ClientDirection.Both, false); c.server = this; // Allow the new client to be rejected by the application if (Connect != null) { if (!Connect(this, c)) { // Rejected cs.Close(); return; } } // Initiate key exchange c.EncryptionType = encType; switch (encType) { case EncryptionType.None: KeyExchangeComplete(c); break; case EncryptionType.ServerKey: c.encKey = GetSymmetricKey(); byte[] key = ClientInfo.GetLengthEncodedVector(c.encKey); cs.Send(key); #if DEBUG Console.Write(c.ID + " Sent key: "); ClientInfo.LogBytes(key, key.Length); #endif c.MakeEncoders(); KeyExchangeComplete(c); break; case EncryptionType.ServerRSAClientKey: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters p = rsa.ExportParameters(true); cs.Send(ClientInfo.GetLengthEncodedVector(p.Modulus)); cs.Send(ClientInfo.GetLengthEncodedVector(p.Exponent)); c.encParams = p; break; default: throw new ArgumentException("Unknown or unsupported encryption type " + encType); } lock (SyncRoot) clients[c.ID] = c; c.BeginReceive(); } catch (ObjectDisposedException) { } catch (SocketException) { } catch (Exception e) { Console.WriteLine(e); } }
internal void KeyExchangeComplete(ClientInfo ci) { // Key exchange is complete on this client. Client ready // handlers may still force a close of the connection if (ClientReady != null) if (!ClientReady(this, ci)) ci.Close("ClientReady callback rejected connection"); }
bool ClientConnect(Server s, ClientInfo ci) { ci.Delimiter = "\r\n\r\n"; ci.Data = new ClientData(ci); ci.OnRead += new ConnectionRead(ClientRead); ci.OnReadBytes += new ConnectionReadBytes(ClientReadBytes); return true; }
static void ReadMessage(ClientInfo ci, uint code, byte[] buf, int len) { Console.WriteLine("Message, code " + code.ToString("X8") + ", content:"); byte[] ba = new byte[len]; Array.Copy(buf, ba, len); Console.WriteLine(" " + ByteBuilder.FormatParameter(new Parameter(ba, ParameterType.Byte))); ci.SendMessage(code, buf, (byte)0, len); }
void ClientRead(ClientInfo ci, string text) { // Read header, if in right state ClientData data = (ClientData)ci.Data; if(data.state != ClientState.Header) return; // already done; must be some text in content, which will be handled elsewhere text = text.Substring(data.headerskip); Console.WriteLine("Read header: "+text+" (skipping first "+data.headerskip+")"); data.headerskip = 0; string[] lines = text.Replace("\r\n", "\n").Split('\n'); data.req.HeaderText = text; // First line: METHOD /path/url HTTP/version string[] firstline = lines[0].Split(' '); if(firstline.Length != 3){ SendResponse(ci, data.req, new HttpResponse(400, "Incorrect first header line "+lines[0]), true); return; } if(firstline[2].Substring(0, 4) != "HTTP"){ SendResponse(ci, data.req, new HttpResponse(400, "Unknown protocol "+firstline[2]), true); return; } data.req.Method = firstline[0]; data.req.Url = firstline[1]; data.req.HttpVersion = firstline[2].Substring(5); int p; for(int i = 1; i < lines.Length; i++){ p = lines[i].IndexOf(':'); if(p > 0) data.req.Header[lines[i].Substring(0, p)] = lines[i].Substring(p+2); else Console.WriteLine("Warning, incorrect header line "+lines[i]); } // If ? in URL, split out query information p = firstline[1].IndexOf('?'); if(p > 0){ data.req.Page = data.req.Url.Substring(0, p); data.req.QueryString = data.req.Url.Substring(p+1); } else { data.req.Page = data.req.Url; data.req.QueryString = ""; } if(data.req.Page.IndexOf("..") >= 0) { SendResponse(ci, data.req, new HttpResponse(400, "Invalid path"), true); return; } if(!data.req.Header.TryGetValue("Host", out data.req.Host)){ SendResponse(ci, data.req, new HttpResponse(400, "No Host specified"), true); return; } string cookieHeader; if(data.req.Header.TryGetValue("Cookie", out cookieHeader)){ string[] cookies = cookieHeader.Split(';'); foreach(string cookie in cookies){ p = cookie.IndexOf('='); if(p > 0){ data.req.Cookies[cookie.Substring(0, p).Trim()] = cookie.Substring(p+1); } else { data.req.Cookies[cookie.Trim()] = ""; } } } string contentLengthString; if(data.req.Header.TryGetValue("Content-Length", out contentLengthString)) data.req.ContentLength = Int32.Parse(contentLengthString); else data.req.ContentLength = 0; //if(data.req.ContentLength > 0){ data.state = ClientState.PreContent; data.skip = text.Length + 4; //} else DoProcess(ci); //ClientReadBytes(ci, new byte[0], 0); // For content length 0 body }
void ReadData(ClientInfo ci, String text) { Console.WriteLine("Received from " + ci.ID + ": " + text); if (text[0] == '!') server.Broadcast(Encoding.UTF8.GetBytes(text)); else ci.Send(text); }
void ClientReadBytes(ClientInfo ci, byte[] bytes, int len) { CleanUpSessions(); int ofs = 0; ClientData data = (ClientData)ci.Data; Console.WriteLine("Reading "+len+" bytes of content, in state "+data.state+", skipping "+data.skip+", read "+data.read); switch(data.state){ case ClientState.Content: break; case ClientState.PreContent: data.state = ClientState.Content; if((data.skip - data.read) > len) { data.skip -= len; return; } ofs = data.skip - data.read; data.skip = 0; break; //case ClientState.Header: data.read += len - data.headerskip; return; default: data.read += len; return; } data.req.Content += Encoding.Default.GetString(bytes, ofs, len-ofs); data.req.BytesRead += len - ofs; data.headerskip += len - ofs; #if DEBUG Console.WriteLine("Reading "+(len-ofs)+" bytes of content. Got "+data.req.BytesRead+" of "+data.req.ContentLength); #endif if(data.req.BytesRead >= data.req.ContentLength){ if(data.req.Method == "POST"){ if(data.req.QueryString == "")data.req.QueryString = data.req.Content; else data.req.QueryString += "&" + data.req.Content; } ParseQuery(data.req); DoProcess(ci); } }