public void IsConnectedTest() { SocketServer target = new SocketServer(); // TODO: 初始化为适当的值 bool actual; actual = target.IsConnected; Assert.Inconclusive( "验证此测试方法的正确性。" ); }
public void ServiceHandleManagerTest() { SocketServer target = new SocketServer(); // TODO: 初始化为适当的值 ServiceHandleManager actual; actual = target.ServiceHandleManager; Assert.Inconclusive( "验证此测试方法的正确性。" ); }
/// <summary> /// Show a select dialog in MediaPortal. After that, send the result to the sender. /// </summary> /// <param name="dialogId">Id of dialog</param> /// <param name="title">Dialog title</param> /// <param name="text">Dialog text</param> /// <param name="options">Options for the user to choose from</param> /// <param name="socketServer">Server</param> /// <param name="sender">Sender of the request</param> internal static void ShowSelectDialog(string dialogId, string title, List<string> options, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { GUIDialogMenu dlgMenu = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); MessageDialogResult result = new MessageDialogResult(); result.DialogId = dialogId; result.YesNoResult = false; if (dlgMenu != null) { dlgMenu.Reset(); dlgMenu.SetHeading(title); if (options != null) { foreach (string o in options) { dlgMenu.Add(o); } } dlgMenu.DoModal(GUIWindowManager.ActiveWindow); if (dlgMenu.SelectedId != -1) { result.YesNoResult = true; result.SelectedOption = dlgMenu.SelectedLabelText; } } }
public MainWindow() { InitializeComponent(); // 시작 시, 연결을 위한 소켓을 비어있는 상태로 생성한다. // 방향키 트리거에 의한 오류방지를 위한 것. server = new SocketServer(); }
/// <summary> /// Handle a "showdialog" message received from a client /// </summary> /// <param name="message">Message</param> /// <param name="socketServer">Socket server</param> /// <param name="sender">Sender</param> internal static void HandleShowDialogMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { String dialogType = (String)message["DialogType"]; String dialogId = (String)message["DialogId"]; if (dialogType != null) { String title = (String)message["Title"]; String text = (String)message["Text"]; if (dialogType.Equals("yesno")) { //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowYesNoThreaded)).Start(new object[] { dialogId, title, text, socketServer, sender }); } else if (dialogType.Equals("ok")) { new Thread(new ParameterizedThreadStart(ShowOkDialogThreaded)).Start(new object[] { title, text }); } else if (dialogType.Equals("yesnoselect")) { List<String> options = new List<String>(); JArray array = (JArray)message["Options"]; if (array != null) { foreach (JValue v in array) { options.Add((string)v.Value); } } //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowYesNoThenSelectThreaded)).Start(new object[] { dialogId, title, text, options, socketServer, sender }); } else if (dialogType.Equals("select")) { List<String> options = new List<String>(); JArray array = (JArray)message["Options"]; if (array != null) { foreach (JValue v in array) { options.Add((string)v.Value); } } //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowSelectThreaded)).Start(new object[] { dialogId, title, options, socketServer, sender }); } else { WifiRemote.LogMessage("Dialog type " + dialogType + " not supported yet", WifiRemote.LogType.Warn); } } else { WifiRemote.LogMessage("No dialog type specified", WifiRemote.LogType.Warn); } }
private void OnLoginEnded(string obj) { Debug.LogWarning (obj); int splitPosition = obj.IndexOf (' '); LoginCallback (obj.Substring (0, splitPosition) == "SUCCESS", obj.Substring (splitPosition + 1)); socketServer.Stop (); socketServer = null; }
public SocketServerWorker(SocketServer _server, TcpClient _client, int _id) { server = _server; id = _id; client = _client; socket = client.Client; Log.AddToDebug(id + "|SocketServerWorker Created"); }
private void btn_Start_Click(object sender, EventArgs e) { try { SocketServer s = new SocketServer(); s.Start(); this.btn_Start.Enabled = false; } catch (Exception ex) { throw; } }
protected override void Login(string facebookAppID) { JavaVM.AttachCurrentThread (); //Find current Activity IntPtr clsActivity = JNI.FindClass ("com/unity3d/player/UnityPlayer"); IntPtr objActivity = JNI.GetStaticObjectField (clsActivity, JNI.GetStaticFieldID (clsActivity, "currentActivity", "Landroid/app/Activity;")); //Create LoginAdapter obj IntPtr clsLAdapter = JNI.FindClass ("com/socialnetwork/LoginAdapter"); IntPtr objlAdapter = JNI.NewObject (clsLAdapter, JNI.GetMethodID (clsLAdapter, "<init>", "(Landroid/app/Activity;)V"), objActivity); IntPtr lAdapter = JNI.NewGlobalRef (objlAdapter); if (JNI.CallBooleanMethod (lAdapter, JNI.GetMethodID (clsLAdapter, "Login", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z"), JNI.NewStringUTF (facebookAppID), JNI.NewStringUTF (host), JNI.NewStringUTF (port.ToString ()), JNI.NewStringUTF ("fb")) == 0) { return; } socketServer = new SocketServer (port); socketServer.ReadString += OnLoginEnded; }
/// <summary> /// Show a yes no dialog in MediaPortal and send the result to the sender /// </summary> /// <param name="dialogId">Id of dialog</param> /// <param name="title">Dialog title</param> /// <param name="text">Dialog text</param> /// <param name="socketServer">Server</param> /// <param name="sender">Sender of the request</param> internal static void ShowYesNoDialog(string dialogId, string title, string text, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { GUIDialogYesNo dlg = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO); if (dlg != null) { dlg.Reset(); dlg.SetHeading(title); dlg.SetLine(1, text); dlg.DoModal(GUIWindowManager.ActiveWindow); MessageDialogResult result = new MessageDialogResult(); result.YesNoResult = dlg.IsConfirmed; result.DialogId = dialogId; socketServer.SendMessageToClient(result, sender); } }
/// <summary> /// Handle an MpExtended message received from a client /// </summary> /// <param name="message">Message</param> /// <param name="socketServer">Socket server</param> /// <param name="sender">Sender</param> internal static void HandleMpExtendedMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { string itemId = (string)message["ItemId"]; int itemType = (int)message["MediaType"]; int providerId = (int)message["ProviderId"]; String action = (String)message["Action"]; Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(message["PlayInfo"].ToString()); int startPos = (message["StartPosition"] != null) ? (int)message["StartPosition"] : 0; if (action != null) { if (action.Equals("play")) { //play the item in MediaPortal WifiRemote.LogMessage("play mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); MpExtendedHelper.PlayMediaItem(itemId, itemType, providerId, values, startPos); } else if (action.Equals("show")) { //show the item details in mediaportal (without starting playback) WifiRemote.LogMessage("play mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); MpExtendedHelper.ShowMediaItem(itemId, itemType, providerId, values); } else if (action.Equals("enqueue")) { //enqueue the mpextended item to the currently active playlist WifiRemote.LogMessage("enqueue mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); int startIndex = (message["StartIndex"] != null) ? (int)message["StartIndex"] : -1; PlayListType playlistType = PlayListType.PLAYLIST_VIDEO; List<PlayListItem> items = MpExtendedHelper.CreatePlayListItemItem(itemId, itemType, providerId, values, out playlistType); PlaylistHelper.AddPlaylistItems(playlistType, items, startIndex); } } else { WifiRemote.LogMessage("No MpExtended action defined", WifiRemote.LogType.Warn); } }
// WPF의 연결버튼에 대한 클릭 이벤트 private void Connect_Server(object sender, RoutedEventArgs e) { // 버튼의 값이 '연결' 일 경우 // 서버와의 연결을 위한 프로세스가 작동한다. if((((Button)sender).Content).Equals("연결")) { if (HOST_IP.Text == null) { MessageBox.Show("아이피를 입력해주세요."); } else { server = new SocketServer(HOST_IP.Text); server.Connect(); if (server.isConnected()) { // 연결에 성공할 경우, 상태를 나타내주는 표시등의 색과 버튼의 내용 등의 설정을 변경한다. // 아이피를 넣는 곳을 읽기전용으로 만드는 이유는 아이피 변경 불가 및 방향키 인식의 오류를 방지하기 위함이다. CONNECT_STATUS.Fill = Brushes.LawnGreen; RESULT_OF_CONNECT.Text = "연결에 성공하였습니다."; HOST_IP.SetValue(TextBox.IsReadOnlyProperty, true); BUTTON.Content = "끊기"; } } } // 그렇지 않을 경우, 서버와의 연결을 끊기위한 것으로 간주하고 처리한다. else { if(server.isConnected()) { server.sendMsg("Close"); server.Close(); CONNECT_STATUS.Fill = Brushes.Red; RESULT_OF_CONNECT.Text = "IP를 입력한 후, 연결버튼을 누르세요."; HOST_IP.SetValue(TextBox.IsReadOnlyProperty, false); BUTTON.Content = "연결"; } } }
public void Starting_a_socket_server() { _startingEventReceived = new Future<ServerStarting>(); _runningEventReceived = new Future<ServerRunning>(); _input = new ChannelAdapter(); _connection = _input.Connect(x => { x.AddConsumerOf<ServerStarting>() .UsingConsumer(_startingEventReceived.Complete) .HandleOnCallingThread(); x.AddConsumerOf<ServerRunning>() .UsingConsumer(_runningEventReceived.Complete) .HandleOnCallingThread(); }); _uri = new Uri("tcp://0.0.0.0:8008"); _server = new SocketServer(_uri, _input); _server.Start(); }
/// <summary> /// Handle an MovingPictures message received from a client /// </summary> /// <param name="message">Message</param> /// <param name="socketServer">Socket server</param> /// <param name="sender">Sender</param> internal static void HandleMovingPicturesMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { string action = (string)message["Action"]; if (!string.IsNullOrEmpty(action)) { // Show movie details for this movie if (action == "moviedetails") { string movieName = (string)message["MovieName"]; if (!string.IsNullOrEmpty(movieName)) { int movieId = MovingPicturesHelper.GetMovieIdByName(movieName); MovingPicturesHelper.ShowMovieDetails(movieId); } } // Play a movie with MovingPictures else if (action == "playmovie") { int movieId = (message["MovieId"] != null) ? (int)message["MovieId"] : -1; string movieName = (string)message["MovieName"]; bool resume = (message["AskToResume"] != null) ? (bool)message["AskToResume"] : true; int startPos = (message["StartPosition"] != null) ? (int)message["StartPosition"] : 0; // Play by movie id if (movieId != -1) { MovingPicturesHelper.PlayMovie(movieId, resume, startPos); } else if (!string.IsNullOrEmpty(movieName)) { // Play by name MovingPicturesHelper.PlayMovie(movieName, resume, startPos); } } } }
private void btn_start_Click(object sender, EventArgs e) { s = new SocketServer(); s.StartServer(showText); btn_start.Enabled = false; }
public void closeSocket(String password = "******") { SocketServer.shutdownSocketServer(password); }
// AVRO-625 [Test] public void CancelPendingRequestsAfterChannelCloseByServerShutdown() { // The purpose of this test is to verify that a client doesn't stay // blocked when a server is unexpectedly killed (or when for some // other reason the channel is suddenly closed) while the server // was in the process of handling a request (thus after it received // the request, and before it returned the response). // Start up a second server so that closing the server doesn't // interfere with the other unit tests: var blockingSimpleImpl = new BlockingSimpleImpl(); var responder = new SpecificResponder <Simple>(blockingSimpleImpl); var server2 = new SocketServer("localhost", 0, responder); server2.Start(); SocketTransceiver transceiver2 = null; try { transceiver2 = new SocketTransceiver("localhost", server2.Port); var simpleClient2 = SpecificRequestor.CreateClient <SimpleCallback>(transceiver2); // Acquire the method-enter permit, which will be released by the // server method once we call it blockingSimpleImpl.acquireEnterPermit(); // Acquire the run permit, to avoid that the server method returns immediately blockingSimpleImpl.acquireRunPermit(); var t = new Thread(() => { try { simpleClient2.add(3, 4); Assert.Fail("Expected an exception"); } catch (Exception) { // expected } }); // Start client call t.Start(); // Wait until method is entered on the server side blockingSimpleImpl.acquireEnterPermit(); // The server side method is now blocked waiting on the run permit // (= is busy handling the request) // Stop the server server2.Stop(); // With the server gone, we expect the client to get some exception and exit // Wait for client thread to exit t.Join(10000); Assert.IsFalse(t.IsAlive, "Client request should not be blocked on server shutdown"); } finally { blockingSimpleImpl.releaseRunPermit(); server2.Stop(); if (transceiver2 != null) { transceiver2.Close(); } } }
protected override async Task InitializeDefaults() { this.instance = await SocketServer.RegisterChannelListener(port, dataFormat); instance.OnMessageReceived += Server_OnMessageReceived; }
public void DualModeBeginConnect_DnsEndPointToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { IAsyncResult async = socket.BeginConnect(new DnsEndPoint("localhost", port), null, null); socket.EndConnect(async); Assert.True(socket.Connected); } }
public void DualModeConnect_IPAddressListToHost_Success(IPAddress[] connectTo, IPAddress listenOn, bool dualModeServer) { int port; using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { socket.Connect(connectTo, port); Assert.True(socket.Connected); } }
/// <summary>Main program</summary> static int Main(string[] args) { try { AppDomain.CurrentDomain.AssemblyResolve += Manager.ResolveManagerAssembliesEventHandler; // Send a command to socket server to get the job to run. object response = GetNextJob(); while (response != null) { JobRunnerMultiProcess.GetJobReturnData job = response as JobRunnerMultiProcess.GetJobReturnData; // Run the simulation. Exception error = null; string simulationName = null; StorageViaSockets storage = new StorageViaSockets(job.key); object[] services = new object[] { storage }; try { IRunnable jobToRun = job.job; if (jobToRun is RunSimulation) { RunSimulation simulationRunner = job.job as RunSimulation; // Replace datastore with a socket writer simulationRunner.Services = services; simulationName = simulationRunner.simulationToRun.Name; } else { Links links = new Links(services); links.Resolve(jobToRun); } jobToRun.Run(new CancellationTokenSource()); } catch (Exception err) { error = err; } // Signal we have completed writing data for this sim. storage.WriteAllData(); // Signal end of job. JobRunnerMultiProcess.EndJobArguments endJobArguments = new JobRunnerMultiProcess.EndJobArguments(); endJobArguments.key = job.key; if (error != null) { endJobArguments.errorMessage = error.ToString(); } endJobArguments.simulationName = simulationName; SocketServer.CommandObject endJobCommand = new SocketServer.CommandObject() { name = "EndJob", data = endJobArguments }; SocketServer.Send("127.0.0.1", 2222, endJobCommand); // Get next job. response = GetNextJob(); } } catch (Exception err) { Console.WriteLine(err.ToString()); return(1); } finally { AppDomain.CurrentDomain.AssemblyResolve -= Manager.ResolveManagerAssembliesEventHandler; } return(0); }
/// <summary> /// Handle an MpExtended message received from a client /// </summary> /// <param name="message">Message</param> /// <param name="socketServer">Socket server</param> /// <param name="sender">Sender</param> internal static void HandleMpExtendedMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { string itemId = (string)message["ItemId"]; int itemType = (int)message["MediaType"]; int providerId = (int)message["ProviderId"]; String action = (String)message["Action"]; Dictionary <string, string> values = JsonConvert.DeserializeObject <Dictionary <string, string> >(message["PlayInfo"].ToString()); int startPos = (message["StartPosition"] != null) ? (int)message["StartPosition"] : 0; if (action != null) { if (action.Equals("play")) { //play the item in MediaPortal WifiRemote.LogMessage("play mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); MpExtendedHelper.PlayMediaItem(itemId, itemType, providerId, values, startPos); } else if (action.Equals("show")) { //show the item details in mediaportal (without starting playback) WifiRemote.LogMessage("show mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); MpExtendedHelper.ShowMediaItem(itemId, itemType, providerId, values); } else if (action.Equals("enqueue")) { //enqueue the mpextended item to the currently active playlist WifiRemote.LogMessage("enqueue mediaitem: ItemId: " + itemId + ", itemType: " + itemType + ", providerId: " + providerId, WifiRemote.LogType.Debug); int startIndex = (message["StartIndex"] != null) ? (int)message["StartIndex"] : -1; PlayListType playlistType = PlayListType.PLAYLIST_VIDEO; List <PlayListItem> items = MpExtendedHelper.CreatePlayListItemItem(itemId, itemType, providerId, values, out playlistType); PlaylistHelper.AddPlaylistItems(playlistType, items, startIndex); } } else { WifiRemote.LogMessage("No MpExtended action defined", WifiRemote.LogType.Warn); } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); #if WINDOWS this.IsMouseVisible = true; #endif // Initialize the GoblinXNA framework State.InitGoblin(graphics, Content, ""); // Initialize the scene graph scene = new Scene(); State.EnableNetworking = true; State.IsServer = isServer; State.ShowNotifications = true; State.ShowFPS = true; Notifier.FadeOutTime = 2000; // Set up the lights used in the scene CreateLights(); // Set up the camera, which defines the eye location and viewing frustum CreateCamera(); // Create 3D objects CreateObject(); // Create a network object that contains mouse press information to be // transmitted over network mouseNetworkObj = new MouseNetworkObject(); // When a mouse press event is sent from the other side, then call "ShootBox" // function mouseNetworkObj.CallbackFunc = ShootBox; // Create a network handler for handling the network transfers INetworkHandler networkHandler = null; #if USE_SOCKET_NETWORK || WINDOWS_PHONE networkHandler = new SocketNetworkHandler(); #else networkHandler = new NetworkHandler(); #endif if (State.IsServer) { IServer server = null; #if WINDOWS #if USE_SOCKET_NETWORK server = new SocketServer(14242); #else server = new LidgrenServer("Tutorial10", 14242); #endif State.NumberOfClientsToWait = 1; scene.PhysicsEngine = new NewtonPhysics(); #else scene.PhysicsEngine = new MataliPhysics(); ((MataliPhysics)scene.PhysicsEngine).SimulationTimeStep = 1 / 30f; #endif scene.PhysicsEngine.Gravity = 30; server.ClientConnected += new HandleClientConnection(ClientConnected); server.ClientDisconnected += new HandleClientDisconnection(ClientDisconnected); networkHandler.NetworkServer = server; } else { IClient client = null; // Create a client that connects to the local machine assuming that both // the server and client will be running on the same machine. In order to // connect to a remote machine, you need to either pass the host name or // the IP address of the remote machine in the 3rd parameter. #if WINDOWS client = new LidgrenClient("Tutorial10", 14242, "Localhost"); #else client = new SocketClient("10.0.0.2", 14242); #endif // If the server is not running when client is started, then wait for the // server to start up. client.WaitForServer = true; client.ConnectionTrialTimeOut = 60 * 1000; // 1 minute timeout client.ServerConnected += new HandleServerConnection(ServerConnected); client.ServerDisconnected += new HandleServerDisconnection(ServerDisconnected); networkHandler.NetworkClient = client; } // Assign the network handler used for this scene scene.NetworkHandler = networkHandler; // Add the mouse network object to the scene graph, so it'll be sent over network // whenever ReadyToSend is set to true. scene.NetworkHandler.AddNetworkObject(mouseNetworkObj); MouseInput.Instance.MousePressEvent += new HandleMousePress(MouseInput_MousePressEvent); }
/// <summary> /// 登录 /// </summary> /// <param name="username">用户名</param> /// <param name="password">密码</param> /// <param name="callback">完成回调</param> public void Login(string username, string password, Action <Hashtable> callback) { loginCallback = callback; SocketServer.GetSingleton().Send("login/login", new object[] { username, password }); }
private void OnDestroy() { SocketServer.GetSingleton().RemoveListener("login/login"); }
private void Awake() { SocketServer.GetSingleton().AddListener("login/login", OnLoginCallback); }
private static void DoSomething(KeyValuePair <TcpClient, byte[]> data, SocketServer server) { Console.WriteLine(((IPEndPoint)data.Key.Client.RemoteEndPoint).Address.ToString() + ": " + Encoding.UTF8.GetString(data.Value)); server.ResponseToClient(data.Key, "received"); }
public override SocketServer.SocketClient AcceptSocket(System.Net.Sockets.Socket s, SocketServer.ConnectMgr cmgr) { TCPRTPSocketClient objNew = new TCPRTPSocketClient(s, cmgr); return objNew; }
private void DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer, int port) { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, port)) { ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler<SocketAsyncEventArgs>(AsyncCompleted); args.RemoteEndPoint = new IPEndPoint(connectTo, port); args.UserToken = waitHandle; socket.ConnectAsync(args); Assert.True(waitHandle.WaitOne(5000), "Timed out while waiting for connection"); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.True(socket.Connected); } }
public WebSocket(SocketServer socketServer, int port) : base(socketServer) { _server = new WebSocketServer(port) { WaitTime = TimeSpan.FromSeconds(1) }; _server.Log.KnownFatal = new List <string>() { "The header of a frame cannot be read from the stream.", "Object name: 'System.Net.Sockets.NetworkStream'." }; _server.WebSocketServices.AddService <WSPeer>("/WebSocket", peer => { peer._OnOpen += () => { IPEndPoint iPEndPoint = peer.Context.UserEndPoint; string clientIp = iPEndPoint.ToString(); if (ClientInstance.ContainsKey(clientIp)) { ClientInstance.Remove(clientIp); } // 建立玩家peer實體 ClientNode cNode = _SocketServer.GetPeer(this, iPEndPoint, _SocketServer); try { //註冊到 mListener 中,讓他的 Receive 功能能被叫 WSInstance instance = new WSInstance(cNode, peer); //註冊到 mListener 中,讓他的 Receive 功能能被叫 ClientInstance.Add(clientIp, instance); //成功加入後傳送 Connect 事件給 Client peer.SendBytes(new byte[] { 1 }); cNode.Initialize(); } catch (Exception e) { Printer.WriteError($"Accept connection failed : {e.Message}\n{e.StackTrace}"); } }; peer._OnMessage += packet => { if (ClientInstance.TryGetValue(peer.Context.UserEndPoint.ToString(), out Instance instance)) { WSInstance client = (WSInstance)instance; client.PassData(packet); } }; peer._OnClose += e => { DisConnect(peer.Context.UserEndPoint); }; peer._OnError += e => { DisConnect(peer.Context.UserEndPoint); }; }); }
private void DualModeConnect_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { socket.Connect(new IPEndPoint(connectTo, port)); Assert.True(socket.Connected); } }
/// <summary> /// Sends key-up so a running key-down is cancelled /// </summary> public static Task <bool> ParseCommandStopRepeatAsync(JObject message, SocketServer server, AsyncSocket sender) { _isCommandDown = false; return(Task.FromResult(true)); }
private void DualModeConnect_DnsEndPointToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { socket.Connect(new DnsEndPoint("localhost", port, AddressFamily.Unspecified)); Assert.True(socket.Connected); } }
static void Main(string[] args) { var server = new SocketServer(); server.Start().Wait(); }
public void Stop() { SocketServer.Stop(); }
public Tcp(SocketServer socketServer, IPEndPoint iPEndPoint) : base(socketServer) { _listener = new TcpListener(IPAddress.IPv6Any, iPEndPoint.Port); _listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); }
public void TestSendAfterChannelClose() { // Start up a second server so that closing the server doesn't // interfere with the other unit tests: var responder = new SpecificResponder <Simple>(new SimpleImpl()); var server2 = new SocketServer("localhost", 0, responder); server2.Start(); try { var transceiver2 = new SocketTransceiver("localhost", server2.Port); try { var simpleClient2 = SpecificRequestor.CreateClient <SimpleCallback>(transceiver2); // Verify that connection works: Assert.AreEqual(3, simpleClient2.add(1, 2)); // Try again with callbacks: var addFuture = new CallFuture <int>(); simpleClient2.add(1, 2, addFuture); Assert.AreEqual(3, addFuture.WaitForResult(2000)); // Shut down server: server2.Stop(); // Send a new RPC, and verify that it throws an Exception that // can be detected by the client: bool ioeCaught = false; try { simpleClient2.add(1, 2); Assert.Fail("Send after server close should have thrown Exception"); } catch (SocketException) { ioeCaught = true; } Assert.IsTrue(ioeCaught, "Expected IOException"); // Send a new RPC with callback, and verify that the correct Exception // is thrown: ioeCaught = false; try { addFuture = new CallFuture <int>(); simpleClient2.add(1, 2, addFuture); addFuture.WaitForResult(2000); Assert.Fail("Send after server close should have thrown Exception"); } catch (SocketException) { ioeCaught = true; } Assert.IsTrue(ioeCaught, "Expected IOException"); } finally { transceiver2.Disconnect(); } } finally { server2.Stop(); Thread.Sleep(1000); } }
/// <summary> /// Handle a "showdialog" message received from a client /// </summary> /// <param name="message">Message</param> /// <param name="socketServer">Socket server</param> /// <param name="sender">Sender</param> internal static void HandleShowDialogMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender) { String dialogType = (String)message["DialogType"]; String dialogId = (String)message["DialogId"]; if (dialogType != null) { String title = (String)message["Title"]; String text = (String)message["Text"]; if (dialogType.Equals("yesno")) { //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowYesNoThreaded)).Start(new object[] { dialogId, title, text, socketServer, sender }); } else if (dialogType.Equals("ok")) { new Thread(new ParameterizedThreadStart(ShowOkDialogThreaded)).Start(new object[] { title, text }); } else if (dialogType.Equals("yesnoselect")) { List <String> options = new List <String>(); JArray array = (JArray)message["Options"]; if (array != null) { foreach (JValue v in array) { options.Add((string)v.Value); } } //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowYesNoThenSelectThreaded)).Start(new object[] { dialogId, title, text, options, socketServer, sender }); } else if (dialogType.Equals("select")) { List <String> options = new List <String>(); JArray array = (JArray)message["Options"]; if (array != null) { foreach (JValue v in array) { options.Add((string)v.Value); } } //show dialog in new thread so we don't block the tcp thread new Thread(new ParameterizedThreadStart(ShowSelectThreaded)).Start(new object[] { dialogId, title, options, socketServer, sender }); } else { WifiRemote.LogMessage("Dialog type " + dialogType + " not supported yet", WifiRemote.LogType.Warn); } } else { WifiRemote.LogMessage("No dialog type specified", WifiRemote.LogType.Warn); } }
public async Task <bool> StartAsync() { return(await SocketServer.StartAsync()); }
public Task StopAsync(CancellationToken cancellationToken) { SocketServer.Stop(); return(Task.CompletedTask); }
public void openSocket(String password = "******") { SocketServer.bootSocketServer(password); }
static void Main(string[] args) { //----- Set Threads! ThreadPool.SetMinThreads(4, 4); ThreadPool.SetMaxThreads(32, 32); SocketServer chatServer = new SocketServer(new ChatSocketService.ChatSocketService()); chatServer.Delimiter = new byte[] { 0xAA, 0xFF, 0xAA }; chatServer.DelimiterType = DelimiterType.dtMessageTailExcludeOnReceive; chatServer.SocketBufferSize = 1024; chatServer.MessageBufferSize = 512; //----- Socket Listener! SocketListener listener = chatServer.AddListener("Char Server", new IPEndPoint(IPAddress.Any, 8090)); listener.AcceptThreads = 3; listener.BackLog = 50; listener.CompressionType = CompressionType.ctNone; listener.EncryptType = EncryptType.etRijndael; listener.CryptoService = new ChatCryptService.ChatCryptService(); chatServer.Start(); Console.WriteLine(" Chat Server Started!"); Console.WriteLine("--------------------------------------"); string key; int iot = 0; int wt = 0; do { Console.WriteLine(" Press T <ENTER> for Threads"); Console.WriteLine(" Press C <ENTER> for Clients"); Console.WriteLine(" Press S <ENTER> for Stop Server"); Console.WriteLine("--------------------------------------"); Console.Write(" -> "); key = Console.ReadLine().ToUpper(); if (key.Equals("T")) { ThreadPool.GetAvailableThreads(out wt, out iot); Console.WriteLine("--------------------------------------"); Console.WriteLine(" I/O Threads " + iot.ToString()); Console.WriteLine(" Worker Threads " + wt.ToString()); Console.WriteLine("--------------------------------------"); } if (key.Equals("C")) { ISocketConnectionInfo[] infos = chatServer.GetConnections(); Console.WriteLine("\r\n--------------------------------------"); Console.WriteLine(" " + infos.Length.ToString() + " user(s)!\r\n"); foreach (ISocketConnectionInfo info in infos) { Console.WriteLine(" Connection Id " + info.ConnectionId.ToString()); Console.WriteLine(" User Name " + ((ConnectionData)info.CustomData).UserName); Console.WriteLine(" Ip Address " + info.RemoteEndPoint.Address.ToString()); Console.WriteLine("--------------------------------------"); } } } while (!key.Equals("S")); Console.WriteLine(" Chat Server Stopping!"); Console.WriteLine("--------------------------------------"); try { chatServer.Stop(); chatServer.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message); } chatServer = null; Console.WriteLine(" Chat Server Stopped!"); Console.WriteLine("--------------------------------------"); Console.ReadLine(); }
//Server button private void button2_Click(object sender, EventArgs e) { sS = new SocketServer(this); }
public override SocketServer.SocketClient AcceptSocket(System.Net.Sockets.Socket s, SocketServer.ConnectMgr cmgr) { UniversalVideoSocketClient objNew = new UniversalVideoSocketClient(s, cmgr); return objNew; }
private void DualModeBeginConnect_LoopbackDnsToHost_Helper(IPAddress listenOn, bool dualModeServer, int port) { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, port)) { IAsyncResult async = socket.BeginConnect("localhost", port, null, null); socket.EndConnect(async); Assert.True(socket.Connected); } }
/// <summary> /// Handle the facade message /// </summary> /// <param name="message">Message sent from client</param> /// <param name="server">Instance of the socket server</param> /// <param name="client">Socket that sent the message (for return messages)</param> internal static void HandleFacadeMessage(Newtonsoft.Json.Linq.JObject message, SocketServer server, AsyncSocket client) { String action = (string)message["FacadeAction"]; GUIWindow currentPlugin = GUIWindowManager.GetWindow(GUIWindowManager.ActiveWindow); if (action.Equals("get")) { MessageFacade returnMessage = new MessageFacade(); if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); List <FacadeItem> items = MpFacadeHelper.GetHomeItems(menu); returnMessage.FacadeItems = items; returnMessage.ViewType = "Home"; } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); if (facade != null) { List <FacadeItem> items = MpFacadeHelper.GetFacadeItems(currentPlugin.GetID, 50); returnMessage.ViewType = facade.CurrentLayout.ToString(); returnMessage.FacadeItems = items; } } returnMessage.WindowId = currentPlugin.GetID; server.SendMessageToClient(returnMessage, client); } else if (action.Equals("setselected")) { if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int selected = (int)message["SelectedIndex"]; facade.SelectedListItemIndex = selected; } } else if (action.Equals("getselected")) { if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { //TODO: find a way to retrieve the currently selected home button } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int selected = facade.SelectedListItemIndex; } } else if (action.Equals("getcount")) { if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); int count = menu.ButtonInfos.Count; } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int count = facade.Count; } } else if (action.Equals("select")) { int selected = (int)message["SelectedIndex"]; if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); MenuButtonInfo info = menu.ButtonInfos[selected]; GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, info.PluginID, 0, null); GUIWindowManager.SendThreadMessage(msg); } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); //TODO: is there a better way to select a list item facade.SelectedListItemIndex = selected; new Communication().SendCommand("ok"); } } else if (action.Equals("context")) { int selected = (int)message["SelectedIndex"]; if (currentPlugin.GetType() == typeof(MediaPortal.GUI.Home.GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); MenuButtonInfo info = menu.ButtonInfos[selected]; GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, info.PluginID, 0, null); GUIWindowManager.SendThreadMessage(msg); } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); //TODO: is there a better way to select a list item facade.SelectedListItemIndex = selected; new Communication().SendCommand("info"); } } }
public XMPPConnection(XMPPClient client, SocketServer.ILogInterface loginterface) : base(loginterface, "") { XMPPClient = client; }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); #if WINDOWS this.IsMouseVisible = true; #endif // Initialize the GoblinXNA framework State.InitGoblin(graphics, Content, ""); // Initialize the scene graph scene = new Scene(); State.EnableNetworking = true; State.IsServer = isServer; State.ShowNotifications = true; State.ShowFPS = true; Notifier.FadeOutTime = 2000; // Set up the lights used in the scene CreateLights(); // Set up the camera, which defines the eye location and viewing frustum CreateCamera(); // Create 3D objects CreateObject(); // Create a network object that contains mouse press information to be // transmitted over network // mouseNetworkObj = new MouseNetworkObject(); networkExchange = new NetworkExchangeWrapper(); // When a mouse press event is sent from the other side, then call "ShootBox" // function //mouseNetworkObj.CallbackFunc = ShootBox; networkExchange.CallbackFunc = ShootBox; // Create a network handler for handling the network transfers INetworkHandler networkHandler = null; #if USE_SOCKET_NETWORK || WINDOWS_PHONE networkHandler = new SocketNetworkHandler(); #else networkHandler = new NetworkHandler(); #endif if (true)//(State.IsServer) { IServer server = null; #if WINDOWS #if USE_SOCKET_NETWORK server = new SocketServer(14242); #else server = new LidgrenServer("Tutorial8_Phone", 14242); #endif State.NumberOfClientsToWait = 1; scene.PhysicsEngine = new NewtonPhysics(); #else scene.PhysicsEngine = new MataliPhysics(); ((MataliPhysics)scene.PhysicsEngine).SimulationTimeStep = 1 / 30f; #endif scene.PhysicsEngine.Gravity = 0; server.ClientConnected += new HandleClientConnection(ClientConnected); server.ClientDisconnected += new HandleClientDisconnection(ClientDisconnected); networkHandler.NetworkServer = server; } // Assign the network handler used for this scene scene.NetworkHandler = networkHandler; // Add the mouse network object to the scene graph, so it'll be sent over network // whenever ReadyToSend is set to true. scene.NetworkHandler.AddNetworkObject(networkExchange); }
private void DualModeConnectAsync_DnsEndPointToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler<SocketAsyncEventArgs>(AsyncCompleted); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.UserToken = waitHandle; socket.ConnectAsync(args); waitHandle.WaitOne(); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.True(socket.Connected); } }
/// <summary> /// 注册服务器,返回一个ITxServer类,再从ITxServer中的startServer一个方法启动服务器 /// </summary> /// <param name="port">端口</param> /// <returns>ITxServer</returns> public static ITxServer startServer(string ip, int port) { ITxServer server = new SocketServer(ip, port); return(server); }
// "None of the discovered or specified addresses match the socket address family." public void Socket_ConnectV4IPAddressListToV4Host_Throws() { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.DualMode = false; int port; using (SocketServer server = new SocketServer(_log, IPAddress.Loopback, false, out port)) { Assert.Throws<ArgumentException>(() => { socket.Connect(new IPAddress[] { IPAddress.Loopback }, port); }); } }
private void Start() { m_SocketServer = new SocketServer(); m_SocketServer.StartSocketServer(); }
public void DualModeConnect_LoopbackDnsToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { socket.Connect("localhost", port); Assert.True(socket.Connected); } }
private void DualModeBeginConnect_IPAddressListToHost_Helper(IPAddress[] connectTo, IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { IAsyncResult async = socket.BeginConnect(connectTo, port, null, null); socket.EndConnect(async); Assert.True(socket.Connected); } }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); string albumName = GetMessageValue <string>(message, "AlbumName"); string id = GetMessageValue <string>(message, "AlbumId"); int discNum = GetMessageValue <int>(message, "DiscNumber"); int trackNum = GetMessageValue <int>(message, "TrackNumber"); int startPos = GetMessageValue <int>(message, "StartPosition"); bool onlyUnwatched = GetMessageValue <bool>(message, "OnlyUnplayedTracks"); // Search for album if (action.Equals("albumsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicAlbumInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetAlbumsByAlbumSearchAsync); SendMessageToClient.Send(new MessageAlbums { Albums = list }, sender, true); } // Show album list else if (action.Equals("albumlist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicAlbumInfo>(client, null, Convert.ToUInt32(count), Convert.ToUInt32(offset), Helper.GetAlbumsByAlbumSearchAsync); SendMessageToClient.Send(new MessageAlbums { Albums = list }, sender, true); } // Search for track if (action.Equals("tracksearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetTracksByTrackSearchAsync); SendMessageToClient.Send(new MessageMusic { Music = list }, sender, true); } // Show track list for album else if (action.Equals("tracklist", StringComparison.InvariantCultureIgnoreCase)) { var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: List Tracks: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var list = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); SendMessageToClient.Send(new MessageMusic { Music = list.Select(i => new MusicInfo(i)).ToList() }, sender, true); } // Show track details for this track else if (action.Equals("tracktails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Play a track else if (action.Equals("playtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Track: AlbumName: {0}, AlbumId: {1}, DiscNumber: {2}, TrackNumber: {3}, StartPos: {4}", albumName, id, discNum, trackNum, startPos); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var episode = await Helper.GetTrackByAlbumTrackAsync(client.UserId, mediaItemGuid.Value, discNum, trackNum); if (!(episode?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find track"); return(false); } await Helper.PlayMediaItemAsync(episode.First().MediaItemId, startPos); } else if (action.Equals("playunplayedtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote Play Track: AlbumName: {0}, AlbumId: {1}", albumName, id); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var tracks = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); if (!(tracks?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find track"); return(false); } var track = tracks.FirstOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); if (track == null) { track = tracks.LastOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") == 100); } if (track == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find tracks"); return(false); } await Helper.PlayMediaItemAsync(track.MediaItemId, 0); } else if (action.Equals("playrandomtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Track: AlbumName: {0}, AlbumId: {1}", albumName, id); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var tracks = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); if (!(tracks?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find tracks"); return(false); } var trackList = tracks?.ToList(); var episodeIndex = new Random().Next(0, trackList.Count - 1); await Helper.PlayMediaItemAsync(trackList[episodeIndex].MediaItemId, 0); } else if (action.Equals("playalbum", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Album: AlbumName: {0}, AlbumId: {1}, OnlyUnplayedTracks: {2}", albumName, id, onlyUnwatched); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Album: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var items = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); IEnumerable <MediaItem> tracks = null; if (onlyUnwatched) { tracks = items.Where(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); } else { tracks = items; } if (!(tracks?.Count() > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Album: Couldn't find any tracks"); return(false); } PlayItemsModel.CheckQueryPlayAction(() => tracks, UI.Presentation.Players.AVType.Audio); } } return(true); }
public void DualModeConnectAsync_Static_DnsEndPointToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler<SocketAsyncEventArgs>(AsyncCompleted); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.UserToken = waitHandle; Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); Assert.True(waitHandle.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.True(args.ConnectSocket.Connected); args.ConnectSocket.Dispose(); } }
public void Start(int port) { SocketServer.Start(port); }
public override SocketServer.SocketClient CreateSocket(System.Net.Sockets.Socket s, SocketServer.ConnectMgr cmgr) { return new UniversalVideoSocketClient(s, cmgr); }
public void TestSocketTransceiverWhenServerStops() { Responder responder = new SpecificResponder <Mail>(new MailImpl()); var server = new SocketServer("localhost", 0, responder); server.Start(); var transceiver = new SocketTransceiver("localhost", server.Port); var mail = SpecificRequestor.CreateClient <Mail>(transceiver); int[] successes = { 0 }; int failures = 0; int[] quitOnFailure = { 0 }; var threads = new List <Thread>(); // Start a bunch of client threads that use the transceiver to send messages for (int i = 0; i < 100; i++) { var thread = new Thread( () => { while (true) { try { mail.send(CreateMessage()); Interlocked.Increment(ref successes[0]); } catch (Exception) { Interlocked.Increment(ref failures); if (Interlocked.Add(ref quitOnFailure[0], 0) == 1) { return; } } } }); thread.Name = "Thread" + i; threads.Add(thread); thread.Start(); } // Be sure the threads are running: wait until we get a good deal of successes while (Interlocked.Add(ref successes[0], 0) < 10000) { Thread.Sleep(50); } // Now stop the server server.Stop(); // Server is stopped: successes should not increase anymore: wait until we're in that situation while (true) { int previousSuccesses = Interlocked.Add(ref successes[0], 0); Thread.Sleep(500); if (previousSuccesses == Interlocked.Add(ref successes[0], 0)) { break; } } server.Start(); long now = CurrentTimeMillis(); int previousSuccesses2 = successes[0]; while (true) { Thread.Sleep(500); if (successes[0] > previousSuccesses2) { break; } if (CurrentTimeMillis() - now > 5000) { Console.WriteLine("FYI: requests don't continue immediately..."); break; } } // Stop our client, we would expect this to go on immediately Console.WriteLine("Stopping transceiver"); Interlocked.Add(ref quitOnFailure[0], 1); now = CurrentTimeMillis(); transceiver.Close(); // Wait for all threads to quit while (true) { threads.RemoveAll(x => !x.IsAlive); if (threads.Count > 0) { Thread.Sleep(1000); } else { break; } } if (CurrentTimeMillis() - now > 10000) { Assert.Fail("Stopping NettyTransceiver and waiting for client threads to quit took too long."); } else { Console.WriteLine("Stopping NettyTransceiver and waiting for client threads to quit took " + (CurrentTimeMillis() - now) + " ms"); } }