public static void testRawServer() { RawServer server = new RawServer("ws://0.0.0.0:20001"); server.onMessage += (string arg1, RawSocket arg2) => { Console.WriteLine("server {0}", arg1); arg2.SendMessage(arg1); }; server.onOpen += (RawSocket obj) => { obj.onClose += (RawSocket) => { Console.WriteLine("server side close"); }; Console.WriteLine("connected ip: {0}, port {1}", obj.address, obj.port); }; }
public static object Create(string eventName, object data) { object res; if (Ready.EventIsThis(eventName)) { res = new Ready((JObject)data); } else if (Resumed.EventIsThis(eventName)) { res = new Resumed((JObject)data); } else if (InvalidSession.EventIsThis(eventName)) { res = (bool)((JValue)data).Value; } else if (Channel.EventIsThis(eventName)) { res = new Channel((JObject)data); } else if (ChannelPinsUpdate.EventIsThis(eventName)) { res = new ChannelPinsUpdate((JObject)data); } else if (EvtServer.EventIsThis(eventName)) { res = new EvtServer((JObject)data); } else if (ServerDelete.EventIsThis(eventName)) { res = ((JObject)data).ToObject <UaServerJson>().id; } else if (ServerUser.EventIsThis(eventName)) { res = new ServerUser((JObject)data, eventName == ServerUser.MemberRemoveId); } else if (ServerUserSet.EventIsThis(eventName)) { res = new ServerUserSet((JObject)data); } else if (ServerUserUpdate.EventIsThis(eventName)) { res = new ServerUserUpdate((JObject)data); } else if (ServerEmojiUpdate.EventIsThis(eventName)) { res = new ServerEmojiUpdate((JObject)data); } else if (RawServer.EventIsThis(eventName)) { res = new RawServer((JObject)data); } else if (ServerRole.EventIsThis(eventName)) { res = new ServerRole((JObject)data); } else if (ServerRoleDelete.EventIsThis(eventName)) { res = new ServerRoleDelete((JObject)data); } else if (Message.EventIsThis(eventName)) { res = new Message((JObject)data, eventName == Message.UpdateId); } else if (RawMessage.EventIsThis(eventName)) { res = new RawMessage((JObject)data, eventName == RawMessage.BulkDeleteId); } else if (Reaction.EventIsThis(eventName)) { res = new Reaction((JObject)data); } else if (ReactionRemoveAll.EventIsThis(eventName)) { res = new ReactionRemoveAll((JObject)data); } else if (Webhook.EventIsThis(eventName)) { res = new Webhook((JObject)data); } else if (EvtUser.EventIsThis(eventName)) { res = new EvtUser((JObject)data); } else if (Unimplemented.EventIsThis(eventName)) { res = Unimplemented.Instance; } else { throw new UnknownEventException("Gateway event \"" + eventName + "\" is unknown."); } DiscordDebug.WriteLine("Heard event: " + eventName + ", handling w/ object " + res.GetType().Name); return(res); }
public void Test1() { Flag fa = new Flag(); Flag fb = new Flag(); try { DummyEncrypter da = new DummyEncrypter(); IRawServer sa = new RawServer(fa, 100, 100, false); TestHelper ta = new TestHelper(); ta.Loop(sa); ta.sl(sa, da, 6800); DummyEncrypter db = new DummyEncrypter(); IRawServer sb = new RawServer(fb, 100, 100, false); TestHelper tb = new TestHelper(); tb.Loop(sb); tb.sl(sb, db, 6801); Thread.Sleep(50); ISingleSocket ca = sa.StartConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6801), null); Thread.Sleep(50); Assert.AreEqual(0, da.externalDummySockets.Count); Assert.AreEqual(0, da.dataIn.Count); Assert.AreEqual(0, da.lostDummySockets.Count); Assert.AreEqual(1, db.externalDummySockets.Count); ISingleSocket cb = db.externalDummySockets[0]; db.externalDummySockets.Clear(); Assert.AreEqual(0, db.dataIn.Count); Assert.AreEqual(0, db.lostDummySockets.Count); ca.Write(new byte[] { (byte)'a', (byte)'a', (byte)'a' }); cb.Write(new byte[] { (byte)'b', (byte)'b', (byte)'b' }); Thread.Sleep(50); Assert.AreEqual(0, da.externalDummySockets.Count); //da.data_in = ca, 'bbb' da.dataIn.Clear(); Assert.AreEqual(0, da.lostDummySockets.Count); Assert.AreEqual(0, db.externalDummySockets.Count); //db.data_in = cb, 'aaa' db.dataIn.Clear(); Assert.AreEqual(0, db.lostDummySockets.Count); ca.Write(new byte[] { (byte)'c', (byte)'c', (byte)'c' }); cb.Write(new byte[] { (byte)'d', (byte)'d', (byte)'d' }); Thread.Sleep(50); Assert.AreEqual(0, da.externalDummySockets.Count); //da.data_in = ca, 'ddd' da.dataIn.Clear(); Assert.AreEqual(0, da.lostDummySockets.Count); Assert.AreEqual(0, db.externalDummySockets.Count); //db.data_in = cb, 'ccc' db.dataIn.Clear(); Assert.AreEqual(0, db.lostDummySockets.Count); ca.Close(); Thread.Sleep(50); Assert.AreEqual(0, da.externalDummySockets.Count); Assert.AreEqual(0, da.dataIn.Count); Assert.AreEqual(0, da.lostDummySockets.Count); Assert.AreEqual(0, db.externalDummySockets.Count); Assert.AreEqual(0, db.dataIn.Count); Assert.AreEqual(1, db.lostDummySockets.Count); db.lostDummySockets.Clear(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { fa.Set(); fb.Set(); } }
public static void StartDownload(Parameters parameters, Flag doneFlag, StatusDelegate statusFunction, ErrorDelegate errorFunction, FinishedDelegate finishedFunction) { if (parameters.ResponseFile.Length == 0 && parameters.Url.Length == 0) { throw new BitTorrentException("需要Response file 或者 Url"); } Parameters = parameters; Stream stream = null; byte[] response; long length = 0; try { if (parameters.ResponseFile.Length != 0) { stream = File.OpenRead(parameters.ResponseFile); length = stream.Length; } else { WebRequest webRequest = WebRequest.Create(parameters.Url); WebResponse webResponse = webRequest.GetResponse(); stream = webResponse.GetResponseStream(); length = webResponse.ContentLength; } response = new byte[length]; stream.Read(response, 0, (int)length); } catch { throw new BitTorrentException("Problem getting response info"); } finally { if (stream != null) { stream.Close(); } } DictNode rootNode; try { rootNode = BEncodingFactory.Decode(response) as DictNode; //BTFormat.CheckMessage(rootNode); } catch { throw new BitTorrentException("got bad file"); } DictNode infoNode = rootNode["info"] as DictNode; List <BitFile> files = new List <BitFile>(); string file; long fileLength; try { if (infoNode.ContainsKey("length")) { fileLength = (infoNode["length"] as IntNode).Value; BytesNode nameNode = (infoNode["name"] as BytesNode); if (nameNode == null) { return; } file = @"k:\torrent\" + nameNode.StringText; Make(file, false); files.Add(new BitFile(file, fileLength)); } else { fileLength = 0L; ListNode filesNode = infoNode["files"] as ListNode; foreach (BEncodedNode handler in filesNode) { DictNode fileNode = infoNode["files"] as DictNode; fileLength += (fileNode["length"] as IntNode).Value; } //访问文件夹 BytesNode nameNode = infoNode["name"] as BytesNode; if (nameNode == null) { return; } file = @"C:\torrent\" + nameNode.StringText; // if this path exists, and no files from the info dict exist, we assume it's a new download and // the user wants to create a new directory with the default name bool existed = false; if (Directory.Exists(file)) { foreach (BEncodedNode handler in filesNode) { DictNode fileNode = handler as DictNode; ListNode pathNode = fileNode["path"] as ListNode; if (File.Exists(Path.Combine(file, (pathNode[0] as BytesNode).StringText))) { existed = true; break; } } if (!existed) { file = Path.Combine(file, (infoNode["name"] as BytesNode).StringText); } } Make(file, true); // alert the UI to any possible change in path //TODO: if (pathFunc != null) // pathFunc(file) foreach (BEncodedNode handler in filesNode) { DictNode fileNode = handler as DictNode; ListNode pathNode = fileNode["path"] as ListNode; string n = file; foreach (BEncodedNode stringHandler in pathNode) { n = Path.Combine(n, (stringHandler as BytesNode).StringText); } files.Add(new BitFile(n, (fileNode["length"] as IntNode).Value)); Make(n, false); } } } catch { throw new BitTorrentException("Couldn't allocate directory..."); } Flag finishFlag = new Flag(); FinishedHelper finishedHelper = new FinishedHelper(); finishedHelper.ErrorFunction = errorFunction; finishedHelper.FinishedFunction = finishedFunction; finishedHelper.DoneFlag = finishFlag; string sID = DateTime.Now.ToLongDateString() + "www.wallywood.co.uk"; byte[] myID = Globals.GetSha1Hash(Encoding.ASCII.GetBytes(sID));//Globals.Sha1.ComputeHash(Encoding.Default.GetBytes(sID)); byte[] piece = (infoNode["pieces"] as BytesNode).ByteArray; List <byte[]> pieces = new List <byte[]>(); for (int i = 0; i < piece.Length; i += 20) { byte[] temp = new byte[20]; Buffer.BlockCopy(piece, i, temp, 0, 20); pieces.Add(temp); } Storage _storage = null; try { try { //_storage = new Storage(files, parameters.AllocatePause, statusFunction); finishedHelper.Storage = _storage; } catch (Exception ex) { errorFunction("trouble accessing files - " + ex.Message); } IntNode pieceLengthNode = infoNode["piece length"] as IntNode; StorageWrapper = new StorageWrapper(_storage, parameters.DownloadSliceSize, pieces, (int)pieceLengthNode.Value, finishedHelper.Finished, finishedHelper.Failed, statusFunction, finishFlag, parameters.CheckHashes, finishedHelper.DataFlunked); } // Catch ValueError // failed("bad data") // catch IO Error catch (Exception ex) { finishedHelper.Failed("Problem - " + ex.Message); } if (finishFlag.IsSet) { return; } RawServer rawServer = new RawServer(finishFlag, parameters.TimeoutCheckInterval, parameters.Timeout, false); if (parameters.MaxPort < parameters.MinPort) { int temp = parameters.MinPort; parameters.MinPort = parameters.MaxPort; parameters.MaxPort = parameters.MinPort; } ushort listenPort; for (listenPort = parameters.MinPort; listenPort <= parameters.MaxPort; listenPort++) { try { rawServer.Bind(listenPort, parameters.Bind, false); break; } catch (SocketException) { //TODO: Error Code } } //TODO: Check whether nothing bound Choker = new Choker(parameters.MaxUploads, rawServer.AddTask, finishFlag); Measure uploadMeasure = new Measure(parameters.MaxRatePeriod, parameters.UploadRateFudge); Measure downloadMeasure = new Measure(parameters.MaxRatePeriod); RateMeasure rateMeasure = new RateMeasure(StorageWrapper.LeftLength); Downloader downloader = new NormalDownloader(StorageWrapper, new PiecePicker(pieces.Count), parameters.RequestBackLog, parameters.MaxRatePeriod, pieces.Count, downloadMeasure, parameters.SnubTime, rateMeasure.DataCameIn); Connecter connecter = new Connecter(downloader, Choker, pieces.Count, StorageWrapper.IsEverythingPending, uploadMeasure, parameters.MaxUploadRate << 10, rawServer.AddTask); byte[] infoHash = Globals.GetSha1Hash(BEncodingFactory.ByteArrayEncode(infoNode));//Globals.Sha1.ComputeHash(BEncodingFactory.ByteArrayEncode(infoNode)); Encrypter encrypter = new Encrypter(connecter, rawServer, myID, parameters.MaxMessageLength, rawServer.AddTask, parameters.KeepAliveInterval, infoHash, parameters.MaxInitiate); //ReRequester reRequester = // new ReRequester((rootNode["announce"] as BytesNode).StringText, parameters.RerequestInterval, // rawServer.AddTask, connecter.GetConnectionsCount, parameters.MinPeers, // encrypter.StartConnect, rawServer.AddExternalTask, // StorageWrapper.GetLeftLength, uploadMeasure.GetTotalLength, downloadMeasure.GetTotalLength, // listenPort, parameters.IP, // myID, infoHash, parameters.HttpTimeout, null, parameters.MaxInitiate, finishFlag); DownloaderFeedback downloaderFeedback = new DownloaderFeedback(Choker, rawServer.AddTask, statusFunction, uploadMeasure.GetUpdatedRate, downloadMeasure.GetUpdatedRate, rateMeasure.GetTimeLeft, rateMeasure.GetLeftTime, fileLength, finishFlag, parameters.DisplayInterval, parameters.Spew); statusFunction("connection to peers", -1, -1, -1, -1); //TODO: finishedHelper.errorfunc finishedHelper.FinishFlag = finishFlag; //finishedHelper.ReRequester = reRequester; finishedHelper.RateMeasure = rateMeasure; //reRequester.d(0); rawServer.ListenForever(encrypter); //reRequester.Announce(2, null); }