Advertisement
Guest User

Untitled

a guest
Jun 5th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.71 KB | None | 0 0
  1. [ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(ICallbackService))]
  2. public interface IService
  3. {
  4. [OperationContract(IsOneWay = true)]
  5. void Login(string email, string password);
  6.  
  7. [OperationContract(IsOneWay = true)]
  8. void Logout(int userId);
  9. }
  10.  
  11. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
  12. public class Service : IService
  13. {
  14. private ServiceHost host = null;
  15. private DuplexChannelFactory<IService> channelFactory = null;
  16. private IService service = null;
  17.  
  18. private static Dictionary<ICallbackService, ICallbackService> pair = new Dictionary<ICallbackService, ICallbackService>();
  19. private static Dictionary<string, ICallbackService> clients = new Dictionary<string, ICallbackService>();
  20.  
  21. private ICallbackService callback;
  22.  
  23.  
  24.  
  25. public Service(InstanceContext context)
  26. {
  27. startService(context);
  28. }
  29.  
  30.  
  31. private void startService(InstanceContext context)
  32. {
  33. host = new ServiceHost(this);
  34. host.Open();
  35. context.Open();
  36. channelFactory = new DuplexChannelFactory<IBattleshipService>(context, "Endpoint");
  37. channelFactory.Open();
  38. service = channelFactory.CreateChannel();
  39.  
  40. callback = context.GetServiceInstance() as ICallbackService;
  41. }
  42.  
  43. private void stopService()
  44. {
  45. if (host != null)
  46. {
  47. if (host.State == CommunicationState.Closed)
  48. {
  49. channelFactory.Close();
  50. host.Close();
  51. }
  52. }
  53. }
  54.  
  55. public void Login(string email, string password)
  56. {
  57.  
  58. User user = getAllUsers().Find(u => u.Email.ToLower() == email.ToLower() && u.Password == password);
  59.  
  60. if (user != null)
  61. {
  62. Console.WriteLine("user : " + email + " has logged in");
  63. clients.Add(email, callback);
  64. callback.Authenticate(true);
  65. }
  66. else callback.Authenticate(false);
  67. }
  68.  
  69. public void Logout(int userId)
  70. {
  71. string email = getUser(userId).Email;
  72. clients.Remove(email);
  73. stopService();
  74. }
  75. }
  76.  
  77. public interface ICallbackService
  78. {
  79.  
  80. [OperationContract(IsOneWay = true)]
  81. void Authenticate(bool authenticated);
  82. }
  83.  
  84. [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Single, UseSynchronizationContext = false)]
  85. public class Client : Service.ICallbackService,
  86. {
  87. public bool Authentication { get; internal set; }
  88.  
  89. public Client()
  90. {
  91. }
  92.  
  93. public void Authenticate(bool authenticated)
  94. {
  95. Console.WriteLine("authentication : " + authenticated);
  96. Authentication = authenticated;
  97. }
  98.  
  99. using System;
  100. using System.Collections.Generic;
  101. using System.ServiceModel;
  102. using System.ServiceModel.Channels;
  103.  
  104. namespace WCFTest
  105. {
  106. class Program
  107. {
  108. public interface ICallbackService
  109. {
  110. [OperationContract(IsOneWay = true)]
  111. void Authenticate(bool authenticated);
  112. }
  113. [ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(ICallbackService))]
  114. public interface IService
  115. {
  116. [OperationContract(IsOneWay = true)]
  117. void Login(string email, string password);
  118.  
  119. [OperationContract(IsOneWay = true)]
  120. void Logout(string email);
  121. }
  122. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
  123. public class Service : IService
  124. {
  125. private Dictionary<string, ICallbackService> _clientDict = new Dictionary<string, ICallbackService>();
  126.  
  127. public void Login(string email, string password)
  128. {
  129. WriteInfoAboutInvoker("Login");
  130.  
  131. // Get client callback
  132. var callback = OperationContext.Current.GetCallbackChannel<ICallbackService>();
  133. lock (_clientDict)
  134. {
  135. _clientDict.Add(email, callback);
  136. Console.WriteLine("Added '{0}'", email);
  137. }
  138. }
  139. public void Logout(string email)
  140. {
  141. WriteInfoAboutInvoker("Logout");
  142. lock (_clientDict)
  143. {
  144. if (_clientDict.ContainsKey(email))
  145. {
  146. _clientDict.Remove(email);
  147. Console.WriteLine("Removed '{0}'", email);
  148. }
  149. }
  150. }
  151. private void WriteInfoAboutInvoker(string method)
  152. {
  153. var ctx = OperationContext.Current;
  154. var msgProp = ctx.IncomingMessageProperties;
  155. var endpoint = msgProp[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
  156.  
  157. Console.WriteLine("Invoked {0} from {1}:{2}. SessionId: {3}", method, endpoint.Address, endpoint.Port, ctx.SessionId);
  158. }
  159. }
  160. public class ServiceClient : IDisposable, ICallbackService, IService
  161. {
  162. private readonly string _cs;
  163. private IService _service;
  164. private DuplexChannelFactory<IService> _channel;
  165. /// <summary>
  166. ///
  167. /// </summary>
  168. /// <param name="cs">Format is 'hostname:port'</param>
  169. public ServiceClient(string cs)
  170. {
  171. if (string.IsNullOrEmpty(cs))
  172. throw new ArgumentException("cs");
  173. _cs = cs;
  174. }
  175. public void Connect()
  176. {
  177. try { InternalConnect(); }
  178. catch (Exception ex)
  179. {
  180. throw new Exception(string.Format("Can't connect to server '{0}'. Error: {1}", _cs, ex.Message));
  181. }
  182. }
  183. public void Dispose()
  184. {
  185. try
  186. {
  187. _channel.Closed -= Channel_Closed;
  188. _channel.Faulted -= Channel_Faulted;
  189. _channel.Close();
  190. }
  191. catch { }
  192. }
  193. private void InternalConnect()
  194. {
  195. InstanceContext ctx = new InstanceContext(this);
  196. NetTcpBinding tcpBinding = CreateBindings();
  197. _channel = new DuplexChannelFactory<IService>(ctx, tcpBinding, new EndpointAddress("net.tcp://" + _cs));
  198. _channel.Closed += Channel_Closed;
  199. _channel.Faulted += Channel_Faulted;
  200. _service = _channel.CreateChannel();
  201. }
  202. void Channel_Closed(object sender, EventArgs e)
  203. {
  204. Console.WriteLine("Channel closed");
  205. }
  206. private NetTcpBinding CreateBindings()
  207. {
  208. NetTcpBinding tcpBinding = new NetTcpBinding();
  209. tcpBinding.CloseTimeout = TimeSpan.FromSeconds(1);
  210. tcpBinding.OpenTimeout = TimeSpan.FromSeconds(2);
  211. tcpBinding.ReceiveTimeout = TimeSpan.FromSeconds(15);
  212. tcpBinding.SendTimeout = TimeSpan.FromSeconds(15);
  213. return tcpBinding;
  214. }
  215. void Channel_Faulted(object sender, EventArgs e)
  216. {
  217. Console.WriteLine("Channel faulted!!!");
  218. }
  219. [Obsolete("This method used only for callback", true)]
  220. public void Authenticate(bool authenticated)
  221. {
  222. Console.WriteLine("authenticated: {0}", authenticated);
  223. }
  224. public void Login(string email, string password)
  225. {
  226. _service.Login(email, password);
  227. }
  228. public void Logout(string email)
  229. {
  230. _service.Logout(email);
  231. }
  232. }
  233. static void Main(string[] args)
  234. {
  235. // args[0] contains mode: server or client
  236. if (args[0] == "server"){
  237. RunServer("localhost:42424");
  238. }
  239. else if (args[0] == "client"){
  240. RunClient("localhost:42424");
  241. }
  242. else{
  243. Console.WriteLine("Unknown mode. Only server or client");
  244. }
  245. }
  246.  
  247. private static void RunClient(string cs)
  248. {
  249. // Create client for our servuce
  250. using (var client = new ServiceClient(cs))
  251. {
  252. // Connect to it
  253. client.Connect();
  254. var fakeEmail = Guid.NewGuid().ToString();
  255. // Call service methods (operation contracts)
  256. client.Login(fakeEmail, fakeEmail);
  257. Console.WriteLine("Invoked Login");
  258.  
  259. Console.WriteLine("Press 'Enter' to call Logout");
  260. Console.ReadLine();
  261.  
  262. client.Logout(fakeEmail);
  263. Console.WriteLine("Invoked Logout");
  264. }
  265. }
  266. static void RunServer(string cs)
  267. {
  268. var service = new Service();
  269.  
  270. var sh = new ServiceHost(service, new Uri("net.tcp://" + cs));
  271. Console.WriteLine("ServiceHost created");
  272. try
  273. {
  274. sh.Open();
  275. }
  276. catch (Exception ex)
  277. {
  278. Console.WriteLine("Couldn't open ServiceHost: {0}", ex);
  279. return;
  280. }
  281. Console.WriteLine("ServiceHost opened");
  282. sh.Closed += ServiceHost_Closed;
  283. sh.Faulted += ServiceHost_Faulted;
  284.  
  285. Console.WriteLine("Press 'Enter' to quit");
  286. Console.ReadLine();
  287. }
  288. private static void ServiceHost_Faulted(object sender, EventArgs e)
  289. {
  290. Console.WriteLine("ServiceHost faulted!!!");
  291. }
  292. private static void ServiceHost_Closed(object sender, EventArgs e)
  293. {
  294. Console.WriteLine("ServiceHost closed");
  295. }
  296. }
  297. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement