My program run 3 times (buttons startCapture-stopCapture, startCapture-stopCapture, then ERROR)
SERVER(class VideoServer, separate from main form)
namespace ChatServer
{
class VideoServer
{
private Thread thrListener;
private Thread thrCapturing;
private TcpListener tlsClient;
bool ServRunning = false;
public static List<tcpclient> ClientList = new List<tcpclient>();
private TcpClient tcpClient;
public Image img;
public Image img1;
public event EventHandler sendPicture;
public Form1 padre;
public VideoServer(Image image, Form1 dad)
{
img = image;
padre = dad;
}
public void StartListening()
{
tlsClient = new TcpListener(3700);
tlsClient.Start();
ServRunning = true;
thrListener = new Thread(KeepListening);
thrListener.Start();
}
private void KeepListening()
{
while (ServRunning == true)
{
tcpClient = tlsClient.AcceptTcpClient();
ConnectionImage newConnection = new ConnectionImage(tcpClient);
}
}
public void StartCapturing()
{
thrCapturing = new Thread(KeepCapturing);
thrCapturing.Start();
}
public void KeepCapturing()
{
while (true)
{
Console.WriteLine("DEBUG: Server--> Entra nel While");
ScreenCapture sc = new ScreenCapture();
img = sc.CaptureScreen();
img1 = (Image)img.Clone();
padre.setImage(img1);
this.SendImage(img);
}
}
public void StopCapturing()
{
thrCapturing.Abort();
}
public static void AddUser(TcpClient tcpUser)
{
ClientList.Add(tcpUser);
}
public static void RemoveUser(TcpClient tcpUser)
{
ClientList.Remove(tcpUser);
}
private void CloseConnection(TcpClient tcpCon)
{
tcpCon.Close();
}
public void SendImage(Image img)
{
for (int i = 0; i < ClientList.Count; i++)
{
TcpClient tempClient = (TcpClient)ClientList[i];
if (tempClient.Connected)
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(tempClient.GetStream(), img);
}
else
{
ClientList.Remove(tempClient);
i--;
}
}
}
}
class ConnectionImage
{
TcpClient tcpCon;
private Thread thrSender;
public ConnectionImage(TcpClient tcpClient)
{
tcpCon=tcpClient;
thrSender = new Thread(AcceptClient);
thrSender.Start();
}
private void AcceptClient()
{
VideoServer.AddUser(tcpCon);
}
}
}
</tcpclient></tcpclient>
CLIENT'S PART
Client = new TcpClient();
Client.Connect("127.0.0.1", 3700);
readingThread = new Thread(new ThreadStart(StartReading));
readingThread.Start();
}
private void StartReading()
{
while (true)
{
NetworkStream stream = Client.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
Image img = (Image)formatter.Deserialize(stream);
pictureBox.Image = img;
}
}