public static IEnumerable <Change> GetChanges(Guid id) { BroadcastClient client = Clients.Where(c => c.ID.Equals(id)).FirstOrDefault(); List <Change> changes = new List <Change>(client == null ? 0 : client.Changes.Count); if (client == null) { return(changes); } lock (chLock[client.User]) { opLock.AcquireReaderLock(-1); try { while (client.Changes.Count > 0) { changes.Add(client.Changes.Dequeue()); } return(changes); } finally { opLock.ReleaseReaderLock(); } } }
public static void Deregister(Guid id) { BroadcastClient client = Clients.Where(c => c.ID.Equals(id)).FirstOrDefault(); if (client == null) { return; } opLock.AcquireWriterLock(-1); try { if (Clients.Where(c => c.User.Equals(client.User)).Count() == 1) { if (chLock.ContainsKey(client.User)) { chLock.Remove(client.User); } } Clients.Remove(client); } finally { opLock.ReleaseWriterLock(); } }
public Form1() { try { _broadcastCallback.BroadcastData += args => rtbAllMessages.Text += args.Message + @"\r\n"; _proxyBroadcast = new BroadcastClient(new InstanceContext(_broadcastCallback)); _proxyBroadcast.ClientCredentials.UserName.UserName = "******"; _proxyBroadcast.ClientCredentials.UserName.Password = "******"; _proxyBroadcast.Connect(); } catch (Exception ex) { MessageBox.Show(ex.InnerException == null ? ex.ToString() : ex.InnerException.ToString()); } //_proxyCardRecognize.Start(); //var bmp = Image.FromFile(@"test.bmp") as Bitmap; //var result = _proxyCardRecognize // .Recognize(new RecoginizeData // { // GameTypeTemplate = GameTemplateType.斗地主手牌, // CardsBitmap = Util.Serialize(bmp.Clone(new Rectangle(280, 590, 400, 50), bmp.PixelFormat)) // }); // result.Result // .ToList() // .ForEach(card => // cardsDisplay += card.Color.ToString() + card.Num.ToString()); InitializeComponent(); }
static void Main(string[] args) { //setup appsettings.json var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); //read configuration values var url = configuration["AzureFunction:url"].ToString(); var code = configuration["AzureFunction:code"].ToString(); //Setup client var client = new BroadcastClient <string>(url, code); client.onMessage = (msg, info) => { Console.WriteLine($"{msg} from {info.fromUser} for group: {info.toGroupName}"); }; Console.WriteLine("Press enter to exit, or message to send."); client.Start(); var input = Console.ReadLine(); while (input != "") { client.Send(input); input = Console.ReadLine(); } }
public static void Broadcast(Guid id, Change change) { opLock.AcquireReaderLock(-1); try { BroadcastClient submiting = Clients.Where(c => c.ID.Equals(id)).First(); lock (chLock[submiting.User]) { foreach (BroadcastClient client in Clients) { if (!client.ID.Equals(id) && client.User.Equals(submiting.User)) { if (change.changeType.Equals(ChangeType.EndOfDay)) { client.Changes.Clear(); } client.Changes.Enqueue(change); } } } } finally { opLock.ReleaseReaderLock(); } }
private void BroadcastTimerCallback() { var gd = JsonConvert.SerializeObject(GameHub.Instance.CurrentGame); var data = Encoding.ASCII.GetBytes(gd); var endpoint = new IPEndPoint(IPAddress.Broadcast, 8888); BroadcastClient?.SendAsync(data, data.Length, endpoint); }
public BroadcastConnectionEstablishmentStrategy(int localPort) { LocalPort = localPort; broadcastClient = new BroadcastClient(localPort); listener = new BroadcastListener(broadcastClient); listener.OnDataReceived += OnDataReceived; broadcaster = new BroadcastTransmitter(broadcastClient); }
protected override void OnExit(ExitEventArgs e) { //关闭所有网络相关服务 BroadcastClient.Stop(); BroadcastServer.Stop(); NetworkClient.Stop(); NetworkServer.Stop(); }
private void Client_ClientConnectedEvent(object obj, ClientConnectedEventArgs e) { broadcastClient = e.BroadcastClient; executeCodeOnUIThread(() => { setAppTaskbarIconState(true); }); }
private void QueryForServerList() { this.Cursor = Cursors.WaitCursor; try { // Define the unique identifier for our service Guid serviceId = new Guid(BroadcastServer.serviceIdString); // Scan the network for services BroadcastClient.ServerResponse[] responses = BroadcastClient.FindServer(serviceId, IPAddress.Parse(Ip), Port, Timeout); foreach (BroadcastClient.ServerResponse response in responses) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(ServerConfig)); StringReader reader = new StringReader(response.Message); try { ServerConfig serverList = xmlSerializer.Deserialize(reader) as ServerConfig; foreach (ServerType sct in serverList.) { String[] v = new string[4] { sct.DisplayName, sct.HostName, sct.Port.ToString(), Dns.GetHostEntry(response.IPAddress).HostName }; AvailableServersView.Items.Add(new ListViewItem(v)); EnableDisable(); Refresh(); } } catch (Exception ex) { throw (new ConfigurationErrorsException( String.Format("Problems reading the message from source {0}.\nMessage = {1}.", response.IPAddress, response.Message), ex)); } } Refresh(); if (responses.Length <= 0) { MessageBox.Show("Configuration information was not available, no broadcast server replied.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Information); } } finally { this.Cursor = Cursors.Default; } }
private void Form1_Load(object sender, EventArgs e) { client = new BroadcastClient <string>(Properties.Settings.Default.AzureFunctionUrl, Properties.Settings.Default.AzureFunctionCode); client.onMessage = (msg, info) => { BeginInvoke((MethodInvoker)(() => { textBox2.Text += $"{msg} from {info.fromUser} for group: {info.toGroupName} {Environment.NewLine} "; })); }; }
protected override void OnLoadedExecute(object obj) { Servers.Clear(); BroadcastClient.ServersChanged -= BroadcastClient_ServersChanged; BroadcastClient.ServersChanged += BroadcastClient_ServersChanged; Task.Factory.StartNew(() => { BroadcastClient.Run(null); }); }
public Form1() { InitializeComponent(); _proxyBroadcast = new BroadcastClient(new InstanceContext(_broadcastCallback)); _proxyBroadcast.ClientCredentials.UserName.UserName = "******"; _proxyBroadcast.ClientCredentials.UserName.Password = "******"; _proxyRecognize.ClientCredentials.UserName.UserName = "******"; _proxyRecognize.ClientCredentials.UserName.Password = "******"; }
public override bool Equals(object obj) { if (obj == null) { return(false); } BroadcastClient val = obj as BroadcastClient; if (val == null) { return(false); } return(this.ID.Equals(val.ID)); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. _spriteBatch = new SpriteBatch(GraphicsDevice); // UNCOMMENT THE GAME HERE _game = new TopDown(Window, Content); //_game = new SurfingGame(Window, Content); //_game = new RpgGame(Window, Content); //_game = new TwitchGame(Window, Content); if (IsNetworkGame) { _broadcastClient = new BroadcastClient(); } }
/// <summary> /// 创建游戏广播接收器 /// </summary> public void CreatGameBroadcastLinker() { broadcastClient = new BroadcastClient(ref Client_receive, ref Client_send);//游戏广播客户端 RequestList_send = new Queue <String>(); CommandList_receive = new Queue <String>(); JoinGame_thread = new Thread(() => { broadcastClient.receiveBroadcast(); broadcastClient.ConnectServer(); broadcastClient.sendResponse(); if (NewServer != null) { NewServer(); } }); //加入游戏线程 JoinGame_thread.IsBackground = true; JoinGame_thread.Start(); //开始接收服务器广播 }
public static Guid Register(string user) { opLock.AcquireWriterLock(-1); try { BroadcastClient newbc = new BroadcastClient(user); Clients.Add(newbc); if (!chLock.ContainsKey(user)) { chLock.Add(user, new object()); } return(newbc.ID); } finally { opLock.ReleaseWriterLock(); } }
private void handleConnectMessage(ConnectMessage connectMessage, TcpClient sender, NetworkMessageReader messageReader) { try { if (connectMessage.BroadCastClient == null) { // close sender.Close(); return; } if (connectMessage.BroadCastClient.Name != null && connectMessage.BroadCastClient.Name.Length > 2) { var newClient = new BroadcastClient(connectMessage.BroadCastClient.Name, ++lastClientID); lock (clients) { clients.Add(new ServerBroadcastClient(newClient, sender)); } NetworkMessageWriter messageWriter = new NetworkMessageWriter(sender); messageWriter.OnErrorStopWritingAndCloseClient = true; messageWriter.WriteError += MessageWriter_WriteError; // send client ConnectMessage Message connectMessage.Connected = true; connectMessage.BroadCastClient = newClient; // modified .. messageWriter.WriteAsync(connectMessage); Logger.log.Info($"client connected {connectMessage.BroadCastClient}"); } else { Logger.log.Warn("BroadCastClient name not ok"); // close sender.Close(); } } catch (Exception ex) { Logger.log.Error(ex); } }
/// <summary> /// 创建广播接收器 /// </summary> public void CreatBroadcastLinker() { broadcastClient = new BroadcastClient(ref Client_receive, ref Client_send); //广播客户端 RequestList_send = new Queue <String>(); MessageList_receive = new Queue <String>(); //ConnectServer_thread = new Thread( () => //{ // while ( true ) // { // broadcastClient.receiveBroadcast(); // broadcastClient.ConnectServer(); // broadcastClient.sendResponse(); // if ( NewServer != null ) // { // NewServer(); // Thread.Sleep(0); // } // } //} );//连接服务器线程 //ConnectServer_thread.IsBackground = true; //ConnectServer_thread.Start();//开始接收服务器广播 }
public Form1() { InitializeComponent(); _proxyBroadcast = new BroadcastClient(new InstanceContext(_broadcastCallback)); _broadcastCallback.BroadcastData += args => { var resultCardType = args.Data.Deserialize() as CardTypeResult; if (!_friendCardTypeResults.Contains(resultCardType, new CardTypeResultComparer())) { _friendCardTypeResults.Add(resultCardType); } //如果友方牌型全部都接受完 if (_friendCardTypeResults.Count == 2) { } }; _proxyRecognize.Start(); _proxyBroadcast.Connect(); }
public BroadcastClientConnectedEventArgs(BroadcastClient broadCastClient) { this.BroadcastClient = broadCastClient; }
static void Main(string[] args) { MessagelibraryServiceCallback objects = new MessagelibraryServiceCallback(); InstanceContext context = new InstanceContext(objects); BroadcastClient client = new BroadcastClient(context); try { List <string> memberId; Console.WriteLine("enter ur name"); string name = Console.ReadLine(); Console.WriteLine("enter id"); string id = Console.ReadLine(); client.RegisterClient(name, id); Console.WriteLine("welcome {0} ", name); Console.WriteLine("Enter 'group' for Group,'peer' for peer to peer chat"); Console.WriteLine("count for active users,exit for closing "); string command = Console.ReadLine(); switch (command) { case "exit": break; case "peer": bool flag = true; Console.WriteLine("enter id to chat with"); memberId = new List <string>(); memberId.Add(Console.ReadLine()); Console.WriteLine("enter messages now and 'exit' to close"); while (flag) { string messagetosend = Console.ReadLine(); switch (messagetosend) { case "exit": flag = false; break; case "count": Console.WriteLine(MessagelibraryServiceCallback.activeClientsCounter); break; default: client.SendMessage(messagetosend, memberId); break; } } break; case "group": Console.WriteLine("enter id's to connect with and'finish' to end adding"); bool idFlag = true; string enterIdsforGroup; memberId = new List <string>(); while (idFlag) { enterIdsforGroup = Console.ReadLine(); if (enterIdsforGroup != "finish") { memberId.Add(enterIdsforGroup); } else { idFlag = false; } } Console.WriteLine("enter messages now or 'exit' to close"); bool flags = true; while (flags) { string commands = Console.ReadLine(); switch (commands) { case "exit": flags = false; break; case "count": Console.WriteLine(MessagelibraryServiceCallback.activeClientsCounter); break; default: client.SendMessage(commands, memberId); break; } } break; default: Console.WriteLine("invalid command"); break; } client.UnRegisterClient(id); client.Close(); Console.WriteLine("closed success"); Console.ReadLine(); } catch (FaultException fe) { Console.WriteLine(fe.Message); client.Abort(); } catch (CommunicationException ce) { Console.WriteLine(ce.Message); client.Abort(); } catch (Exception) { client.Abort(); throw; } }
/// <summary> /// 创建广播接收器 /// </summary> public void CreatBroadcastLinker() { broadcastClient = new BroadcastClient( ref Client_receive, ref Client_send );//广播客户端 RequestList_send = new Queue<String>(); MessageList_receive = new Queue<String>(); //ConnectServer_thread = new Thread( () => //{ // while ( true ) // { // broadcastClient.receiveBroadcast(); // broadcastClient.ConnectServer(); // broadcastClient.sendResponse(); // if ( NewServer != null ) // { // NewServer(); // Thread.Sleep(0); // } // } //} );//连接服务器线程 //ConnectServer_thread.IsBackground = true; //ConnectServer_thread.Start();//开始接收服务器广播 }
public VoiceMessage(BroadcastClient sender, byte[] data) { this.Sender = sender; this.Data = data; }
/// <summary> /// 创建游戏广播接收器 /// </summary> public void CreatGameBroadcastLinker() { broadcastClient = new BroadcastClient(ref Client_receive, ref Client_send);//游戏广播客户端 RequestList_send = new Queue<String>(); CommandList_receive = new Queue<String>(); JoinGame_thread = new Thread(() => { broadcastClient.receiveBroadcast(); broadcastClient.ConnectServer(); broadcastClient.sendResponse(); if (NewServer!=null) { NewServer(); } });//加入游戏线程 JoinGame_thread.IsBackground = true; JoinGame_thread.Start();//开始接收服务器广播 }
public ConnectMessage(BroadcastClient client) { this.BroadCastClient = client; }
protected override void OnUnloadedExecute(object obj) { BroadcastClient.Stop(); }
public ClientConnectedEventArgs(BroadcastClient broadcastClient) { BroadcastClient = broadcastClient; }
public void ProcessRequest(HttpContext context) { HttpRequest Request = context.Request; HttpResponse Response = context.Response; BroadcastClient client = null; BroadcastInput input = null; Error error = null; if (Request.Url.AbsolutePath.EndsWith("/broadcast/register")) { client = ReadBodyAsBroadcastClient(Request); if (client == null || string.IsNullOrEmpty(client.User) || string.IsNullOrWhiteSpace(client.User)) { Response.StatusCode = 400; Response.ContentType = "application/json"; error = new Error(); error.ID = NewID; error.TID = ThreadID; error.PID = ProcessID; error.Message = "The User is missing."; error.StatusCode = 400; error.TimeStamp = DateTime.UtcNow; Response.Write(JsonConvert.SerializeObject(error)); context.ApplicationInstance.CompleteRequest(); return; } string guid = BroadcastClient.Register(client.User).ToString(); Response.StatusCode = 201; Response.ContentType = "application/json"; Response.Write("{\"Result\":{\"ID\":\"" + guid + "\"}}"); context.ApplicationInstance.CompleteRequest(); return; } else if (Request.Url.AbsolutePath.EndsWith("/broadcast/broadcast")) { input = ReadBodyAsBroadcastInput(Request); if (input == null || input.Change == null) { Response.StatusCode = 400; Response.ContentType = "application/json"; error = new Error(); error.ID = NewID; error.TID = ThreadID; error.PID = ProcessID; error.Message = "Invalid request body."; error.StatusCode = 400; error.TimeStamp = DateTime.UtcNow; Response.Write(JsonConvert.SerializeObject(error)); context.ApplicationInstance.CompleteRequest(); return; } BroadcastClient.Broadcast(input.ID, input.Change); Response.StatusCode = 202; Response.ContentType = "application/json"; context.ApplicationInstance.CompleteRequest(); return; } else if (Request.Url.AbsolutePath.EndsWith("/broadcast/changes")) { input = ReadBodyAsBroadcastInput(Request); if (input == null) { Response.StatusCode = 400; Response.ContentType = "application/json"; error = new Error(); error.ID = NewID; error.TID = ThreadID; error.PID = ProcessID; error.Message = "Invalid request body."; error.StatusCode = 400; error.TimeStamp = DateTime.UtcNow; Response.Write(JsonConvert.SerializeObject(error)); context.ApplicationInstance.CompleteRequest(); return; } string changes = "{\"Result\":" + JsonConvert.SerializeObject(BroadcastClient.GetChanges(input.ID)) + "}"; Response.StatusCode = 200; Response.ContentType = "application/json"; Response.Write(changes); context.ApplicationInstance.CompleteRequest(); return; } else if (Request.Url.AbsolutePath.EndsWith("/broadcast/deregister")) { input = ReadBodyAsBroadcastInput(Request); if (input == null) { Response.StatusCode = 400; error = new Error(); error.ID = NewID; error.TID = ThreadID; error.PID = ProcessID; error.Message = "Invalid request body."; error.StatusCode = 400; error.TimeStamp = DateTime.UtcNow; Response.Write(JsonConvert.SerializeObject(error)); context.ApplicationInstance.CompleteRequest(); return; } BroadcastClient.Deregister(input.ID); Response.StatusCode = 200; Response.ContentType = "application/json"; context.ApplicationInstance.CompleteRequest(); return; } Response.StatusCode = 404; Response.ContentType = "application/json"; error = new Error(); error.ID = NewID; error.TID = ThreadID; error.PID = ProcessID; error.Message = "Resource not found"; error.StatusCode = 404; error.TimeStamp = DateTime.UtcNow; Response.Write(JsonConvert.SerializeObject(error)); context.ApplicationInstance.CompleteRequest(); return; }
public void SendDiscoveryRequest_TwoServersRespond() { // This test should test with more than one server but that would mean to have more local ips // to bind to var ips = GetAllIpv4Addresses().ToList(); var closetEndpoints = FindMostPopulatedSubnet(ips); if (closetEndpoints.Count <= 1) { Assert.True(false, "System does not have more than 1 IP in the same 255.255.255.0 subnet to test with"); } var received = new List <Tuple <ServerDiscoveryResponse, IpEndpoint> >(); using (var serverDiscovery = new BroadcastClient(new IpEndpoint(closetEndpoints.First(), 4000), 4338, 3, new NullTrace())) { var serializer = new Serializer <ISerializableMessage>(); serializer.AddType <ServerDiscoveryResponse>(); serializer.AddType <ServerDiscoveryRequest>(); var typedConnection = new TypedConnection <ISerializableMessage>(serverDiscovery.Connection, serializer); typedConnection.NewMessage += (p1, p2, p3) => { received.Add(Tuple.Create((ServerDiscoveryResponse)p2, serverDiscovery.CurrentEndpoint)); }; serverDiscovery.StartReceiving(); var amountConnections = new int[1]; var servers = new List <Server>(); ips = closetEndpoints; int amountOfServer = ips.Count; for (int i = 0; i < amountOfServer; i++) { var copyOfi = i + 1; var server = new Server(new ServerConfiguration(new IpEndpoint(ips[i], 4338)), new NullTrace()); server.NewServerPeer += (server1, serverPeer) => { serverPeer.NewConnection += (p1, p2) => { amountConnections[0]++; int runningId = 0; var typed = new TypedConnection <ISerializableMessage>(p2, serializer); typed.NewMessage += (p3, p4, p5) => { var request = ((ServerDiscoveryRequest)p4); var response = new ServerDiscoveryResponse { ServerVersion = request.ClientVersion * copyOfi, RunningId = runningId++ }; typed.Send(response); }; }; }; servers.Add(server); server.StartReceiving(); } try { for (int i = 0; i < 100; i++) { var receivedBefore = received.Count; typedConnection.Send(new ServerDiscoveryRequest() { ClientVersion = i }); System.Threading.Thread.Sleep(1); Assert.True(Wait.UntilTrue(() => receivedBefore + amountOfServer == received.Count)); } Assert.Equal(amountOfServer * 100, received.Count); for (var index = 0; index < ips.Count; index++) { var ipAddress = ips[index]; var byIp = received.Where(_ => _.Item2.IpAddress.Equals(ipAddress)).ToList(); Assert.Equal(100, byIp.Count); byIp.Sort((p1, p2) => p1.Item1.ServerVersion.CompareTo(p2.Item1.ServerVersion)); Assert.Equal(Enumerable.Range(0, 100).Select(_ => _ * (1 + index)), byIp.Select(_ => _.Item1.ServerVersion)); } } finally { foreach (var server in servers) { server.Dispose(); } } } }