Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Net.Sockets;
- using System.Net;
- namespace Server
- {
- public partial class ServerMainForm : Form
- {
- TcpListener Listener;
- List<Client> ClientList = new List<Client>();
- public ServerMainForm()
- {
- InitializeComponent();
- StartStropListening();
- }
- private void StartStropListening()
- {
- try
- {
- if (button1.Text == "Start")
- {
- Listener = new TcpListener(IPAddress.Any, Convert.ToInt32(textBox1.Text));
- Listener.Start();
- Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), Listener);
- button1.Text = "Stop";
- }
- else
- {
- Listener.Stop();
- button1.Text = "Start";
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- private void AcceptClient(IAsyncResult ar)
- {
- try
- {
- Client client = new Client(Listener.EndAcceptTcpClient(ar));
- client.DataRecievedEvent += DataRecieved;
- client.ClientExitedEvent += ClientExited;
- ClientList.Add(client);
- SetText("Clients connected: " + ClientList.Count);
- // ClientsConnectedLabel.Text = "Clients connected: " + ClientList.Count;
- //call this to accept next client...
- Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), Listener);
- }
- catch (Exception)
- {
- throw;
- }
- }
- private void button1_Click(object sender, EventArgs e)
- {
- StartStropListening();
- }
- private void DataRecieved(Byte[] data)
- {
- //just to let the server know that globally there is data recieved...
- }
- private void ClientExited(Client client)
- {
- // the client exited event was raised thus we need to remove them fromt he list...
- ClientList.Remove(client);
- SetText("Clients connected: " + ClientList.Count);
- }
- delegate void SetTextCallback(string text);
- private void SetText(string text)
- {
- // InvokeRequired required compares the thread ID of the
- // calling thread to the thread ID of the creating thread.
- // If these threads are different, it returns true.
- if (ClientsConnectedLabel.InvokeRequired)
- {
- SetTextCallback d = new SetTextCallback(SetText);
- this.Invoke(d, new object[] { text });
- }
- else
- {
- this.ClientsConnectedLabel.Text = text;
- }
- }
- private void button2_Click(object sender, EventArgs e)
- {
- ClientList[0].SendMessage("hello world! :P ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment