使用TCP服务器侦听多个客户端

时间:2016-04-25 13:25:38

标签: c# tcp

我们只是用TCP服务器做一个小测验。我们可以将一个客户端连接到服务器,但多个服务器崩溃。忽略它里面的荷兰人。 可能有一些非逻辑的东西因为我们已经玩了几个小时。

我们的服务器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;

namespace Simpele_Server
{
class Program
{
    const int portNr = 2000;        
    static void Main(string[] args)
    {
        Program obj = new Program();
        string antwoord = "";
        string client1Ant = "";
        string client2Ant = "";
        string client3ant = "";
        System.Net.IPAddress localAddress = System.Net.IPAddress.Parse("10.145.4.43");
        //Luister op het eigen IP-adres: 127.0.0.1 (Loop back adres)
        TcpListener mijnListener = new TcpListener(localAddress, portNr);
        mijnListener.Start();
        Console.WriteLine("\n Wachten op verbinding...\n");
        while (true)
        {
        //Aanvaard het binnenkomende verzoek
        TcpClient eenClient = mijnListener.AcceptTcpClient();

        //Gebruik een 'NetworkStream object' om gegevens te verzenden en te ontvangen
        NetworkStream ns = eenClient.GetStream();
        byte[] data = new byte[eenClient.ReceiveBufferSize];

        //Lees de binnenkomende 'stream' --> Read() is een 'blocking call'
        int numBytesRead = ns.Read(data, 0,System.Convert.ToInt32(eenClient.ReceiveBufferSize));
        antwoord = Encoding.ASCII.GetString(data, 0, numBytesRead);



        if (antwoord.Substring(0, 8).Equals("Client1:"))
        {
            client1Ant = antwoord;

            Console.WriteLine(obj.ControleerAntwoorden1(client1Ant));
        }
        if (antwoord.Substring(0, 8).Equals("Client2:"))
        {
            client1Ant = antwoord;
            Console.WriteLine(obj.ControleerAntwoorden2(client2Ant));
        }
        if (antwoord.Substring(0, 8).Equals("Client3:"))
        {
            client1Ant = antwoord;
            Console.WriteLine(obj.ControleerAntwoorden3(client3ant));
        }

        //Beeld de ontvangen data af
        Console.WriteLine("Ontvangen: " + antwoord);
    }
        //Voorkom onmiddellijk sluiten van het venster
        Console.ReadLine();
    }

    private int ControleerAntwoorden1(string antwoord)
    {
        int punten = 0;
        string antw;
        antw = antwoord.Replace("Client1:", "");
        //antw = antwoord.Replace("Client2:", "");
        //antw = antwoord.Replace("Client3:", "");
        Console.WriteLine(antw);



        string ant1 = antw.Substring(0, 1);
        string ant2 = antw.Substring(1, 1);
        string ant3 = antw.Substring(2, 1);
        string ant4 = antw.Substring(3, 1);


        if (ant1.Equals("1"))
            punten++;
        if (ant2.Equals("2"))
            punten++;

        if (ant3.Equals("3"))
            punten++;
        if (ant4.Equals("4"))
            punten++;

        return punten;
    }
    private int ControleerAntwoorden2(string antwoord)
    {
        int punten = 0;
        string antw;
        //antw = antwoord.Replace("Client1:", "");
        antw = antwoord.Replace("Client2:", "");
        //antw = antwoord.Replace("Client3:", "");
        Console.WriteLine(antw);



        string ant1 = antw.Substring(0, 1);
        string ant2 = antw.Substring(1, 1);
        string ant3 = antw.Substring(2, 1);
        string ant4 = antw.Substring(3, 1);


        if (ant1.Equals("1"))
            punten++;
        if (ant2.Equals("2"))
            punten++;

        if (ant3.Equals("3"))
            punten++;
        if (ant4.Equals("4"))
            punten++;

        return punten;
    }
    private int ControleerAntwoorden3(string antwoord)
    {
        int punten = 0;
        string antw;
        //antw = antwoord.Replace("Client1:", "");
        //antw = antwoord.Replace("Client2:", "");
        antw = antwoord.Replace("Client3:", "");
        Console.WriteLine(antw);



        string ant1 = antw.Substring(0, 1);
        string ant2 = antw.Substring(1, 1);
        string ant3 = antw.Substring(2, 1);
        string ant4 = antw.Substring(3, 1);


        if (ant1.Equals("1"))
            punten++;
        if (ant2.Equals("2"))
            punten++;

        if (ant3.Equals("3"))
            punten++;
        if (ant4.Equals("4"))
            punten++;

        return punten;
    }
}
}

我们的客户:

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;

namespace client
 {
  public partial class Form1 : Form
  {
      const int poortNr = 2000;
    //string ipadres = "127.0.0.1";
    string ipadres = "10.145.4.43";
    string strRead = null;
    int intBytesRead;
    string[] vragen = { "1. In welk jaar is 9/11 gebeurt?" + Environment.NewLine + "    A = 2001"  + Environment.NewLine + "    B = 2000 " + Environment.NewLine + "    C = 1999" + Environment.NewLine + "    D = 1998",
                      "2. Welke kleur heeft een wolk?" + Environment.NewLine + "     A = Blauw " + Environment.NewLine + "     B = Groen " + Environment.NewLine + "     C = Wit " + Environment.NewLine + "     D = geel",
                      "3. Leeft Steve Jobs nog? " + Environment.NewLine + "    A = Nee " + Environment.NewLine + "    B = Ja " + Environment.NewLine + "    C = Steve jobs heeft nooit bestaan " + Environment.NewLine + "    D = test",
                      "4. test"};
    string antwoorden = "";
    int counter;
    int aantalcounter = 2;
    int vraagnr = 0;
    TcpClient mijnClient = new TcpClient();



    private void startTimer()
    {
        counter = aantalcounter;
        timer1.Start();
        timer1.Interval = 1000;
    }

    private void resetTimer()
    {
        counter = aantalcounter;
        timer1.Stop();
        timer1.Start();
    }

    private void stopTimer()
    {
        timer1.Stop();
    }

    public NetworkStream getNS()
    {
        //networkstream
        NetworkStream mijnNS = mijnClient.GetStream();
        return mijnNS;
    }

    public void disableRadiobuttons()
    {
        radioButton1.Enabled = false;
        radioButton2.Enabled = false;
        radioButton3.Enabled = false;
        radioButton4.Enabled = false;
    }

    public void uncheckRadiobuttons()
    {
        radioButton1.Checked = false;
        radioButton2.Checked = false;
        radioButton3.Checked = false;
        radioButton4.Checked = false;
    }

    //verzend data naar server
    public void verzendData(string tekst)
    {
        byte[] aDataTeVersturen = Encoding.ASCII.GetBytes(tekst);

        getNS().Write(aDataTeVersturen, 0, aDataTeVersturen.Length);
    }

    //zoek selected antwoord
    public string getAntwoord()
    {
        string qsdf = "Client1: ";
        string answer = "";
        if (radioButton1.Checked == true)
        {
            answer = "1";
        }
        if (radioButton2.Checked == true)
        {
            answer = "2";
        }
        if (radioButton3.Checked == true)
        {
            answer = "3";
        }
        if (radioButton4.Checked == true)
        {
            answer = "4";
        }
        if (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false && radioButton4.Checked == false)
        {
            answer = "0"; //geen antwoord
        }
        qsdf += answer; 
        return qsdf;
    }

    //alle antwoorden opslaan in lange string
    public void opslaanAntwoorden(string antwoord)
    {
        antwoorden += antwoord;
    }


    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        txtVraag.Text = vragen[vraagnr];
        startTimer();
        try
        {
            mijnClient.Connect(ipadres, poortNr);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void btnVerbreek_Click(object sender, EventArgs e)
    {
        getNS().Close();
        mijnClient.Close();
        Application.Exit();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {

    }

    private void txtAntwoord_TextChanged(object sender, EventArgs e)
    {

    }

    private void btnOntvang_Click(object sender, EventArgs e)
    {
        //data van server krijgen
        byte[] aDataOntvangen = new byte[Convert.ToInt32(mijnClient.ReceiveBufferSize)];
        intBytesRead = getNS().Read(aDataOntvangen, 0, Convert.ToInt32(mijnClient.ReceiveBufferSize));
        strRead = Encoding.ASCII.GetString(aDataOntvangen, 0, intBytesRead);
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {

    }

    private void txtVraag_TextChanged(object sender, EventArgs e)
    {

    }

    private void timer1_Tick_1(object sender, EventArgs e)
    {
        txtCount.Text = counter.ToString();
        counter--;
        if (counter == -1)
        { 
            resetTimer();
            startTimer();

            opslaanAntwoorden(getAntwoord()); //antwoorden opslaan in 1 lange string

            if (vraagnr != vragen.Length-1)
            {
                txtVraag.Text = vragen[vraagnr + 1];
                volgendeVraag();
                uncheckRadiobuttons();
            }
            else
            {
                verzendData(antwoorden); //zend alle antwoorden (einde van quiz)
                txtVraag.Text = "Einde van quiz";
                uncheckRadiobuttons();
                disableRadiobuttons();

                //timer op 0 + stoppen
                stopTimer();
                counter = 0;
                txtCount.Text = counter.ToString();
            }

        }



    }
    private void volgendeVraag()
    {
        vraagnr++;
    }

    private void label2_Click(object sender, EventArgs e)
    {

    }

    private void radioButton4_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void radioButton3_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void lblCount_Click(object sender, EventArgs e)
    {

    }

}
}

0 个答案:

没有答案