/// <summary> /// Disconnect networkStream from server and send message. /// </summary> /// <param name="n"></param> /// <param name="message"></param> protected async void disconnect(NetworkStream n, string message) { lock (networkStreamPool) { networkStreamPool.Remove(n); } await Task.Yield(); ErrorCommand error = new ErrorCommand(message); await error.SendAsync(n); n.Close(); }
protected async void accept(Socket socket) { await Task.Yield(); socket.BeginAccept((ar) => { Socket s = socket.EndAccept(ar); NetworkStream sns = new NetworkStream(s); lock (networkStreamPool) { networkStreamPool.Add(sns); } handshake(sns); accept(socket); }, socket); }
/// <summary> /// Connect to server with specified url and port. /// </summary> /// <param name="url">Url where to connect. <code>IPAddress</code> is got by <code>IPAddress.Parse(url)</code>.</param> /// <param name="port">Port where to connect.</param> /// <see cref="IPAddress"/> /// <see cref="IPAddress.Parse"/> /// <returns></returns> public async Task <GameTypeCommand> ConnectAsync(string url, int port) { IPAddress ipAddress = null; try { ipAddress = IPAddress.Parse(url); } catch (FormatException e) { throw new FormatException(e.Message); } if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } IPEndPoint ipe = new IPEndPoint(ipAddress, port); await Task.Yield(); ManualResetEvent waitHandle = new ManualResetEvent(false); socket.BeginConnect(ipe, (ar) => { try { socket.EndConnect(ar); } catch { throw new Exception("Cannot connect to server. Is server running?"); } try { COMMUNICATION = new NetworkStream(socket); } catch (TypeInitializationException e) { if (e.InnerException != null) { throw e.InnerException; } } handShake(); waitHandle.Set(); }, socket); waitHandle.WaitOne(); return((GameTypeCommand)await COMMUNICATION.ReceiveCommandAsync()); }
protected async void handshake(NetworkStream sns) { HandShakeProtocol handshakeProtocol = new HandShakeProtocol(); await Task.Yield(); AProtocol protocol = await handshakeProtocol.HandShakeServer(sns); if (protocol == null) { disconnect(sns, "Handshake fail."); } else { sns.PROTOCOL = protocol; await sns.SendCommandAsync(GetGameTypeCommand(Battlefield)); if (!Battlefield.AddRobot(sns)) { disconnect(sns, "Arena is full."); } } }