I'm watching this video to learn the basics on C# async communication. I'm using Microsoft Visual Studio 2013.
In this line:
_networkStream.Add(client.GetStream());
I'm getting this error:
'System.Collections.Generic.List' does not contain a definition for 'GetStream and no extension method 'GetStream' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)
Currently here's the code I have copied while watching the tutorial:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Networking
{
public class ServerManager
{
public int Port { get; set; }
private TcpListener _listener;
private List<TcpClient> _client;
private List<NetworkStream> _networkStream;
public ServerManager(int port)
{
// Assigning Port from the parameter.
Port = port;
// Initialize the _listener to the port specified on the constructor.
_listener = new TcpListener(new IPEndPoint(IPAddress.Any, Port));
// Initialize the _client sockets list.
_client = new List<TcpClient>();
// Initialize the _networkStream which is useful for sending and receiving data.
_networkStream = new List<NetworkStream>();
}
public void Start()
{
// Starts the _listener to listen.
_listener.Start();
_listener.BeginAcceptTcpClient(new AsyncCallback(ClientConnect), null);
}
public void Stop()
{
// Closes all the _client sockets and the network stream.
for (int i = 0; i < _client.Count; i++)
{
_client[i].Close();
_networkStream[i].Close();
}
// Stops the listener. The socket which listens and accept incoming client sockets.
_listener.Stop();
}
private void ClientConnect(IAsyncResult ar)
{
// When any client connects.
// Accept the connection.
TcpClient client = _listener.EndAcceptTcpClient(ar);
// Add on our client list.
_client.Add(client);
// Add the client's stream on our network stream.
_networkStream.Add(_client.GetStream());
Thread threadReceive = new Thread(new ParameterizedThreadStart(ClientReceiveData), null);
threadReceive.Start(_client.Count);
// Accept the next connection.
_listener.BeginAcceptTcpClient(new AsyncCallback(ClientConnect), null);
}
private void ClientReceiveData(object obj)
{
throw new NotImplementedException();
}
}
}
Based from MSDN, TcpClient.GetStream
method is under the namespace System.Net.Sockets
, which I have already included without errors. And so, why am I getting the error?
_client
is instance of List
, client
is instance of TcpClient
. You need to use client.GetStream()
instead of _client.GetStream()
.
_networkStream.Add(client.GetStream());