Advertisement
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;
- using System.Net.Sockets;
- using System.Threading;
- namespace Tuan3_Bai1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- CheckForIllegalCrossThreadCalls = false;
- }
- /*********** Data structure ***********/
- public IPAddress ipAd;
- public int port;
- public TcpListener server;
- public int count = 0;
- public Socket[] socket = new Socket[100];
- public string[] sum = new string[100];
- public List<int> isUsed = new List<int>();
- public bool check = true;
- private void Btn_Start_Click(object sender, EventArgs e)
- {
- Btn_Start.Enabled = false;
- StartServer();
- //serves multiple clients
- Thread t = new Thread(connect);
- t.IsBackground = true;
- t.Start();
- }
- public void StartServer()
- {
- ipAd = IPAddress.Parse(txt_IP.Text);
- port = int.Parse(txt_Port.Text);
- server = new TcpListener(ipAd, port);
- server.Start();
- count = 0;
- }
- public int testconnect(Socket socket)
- {
- return 0;
- }
- //Threading
- public void connect()
- {
- while (true)
- {
- //accept a new connection
- socket[count] = server.AcceptSocket();
- count++;//should use lock here
- //break main flow into main + ServeClientConcurrently flow
- isUsed.Add(1);
- if (check != true)
- {
- int pos = 0;
- foreach (int i in isUsed)
- {
- if (i == 0)
- {
- count = pos+1;
- break;
- }
- pos++;
- }
- isUsed[pos] = 1;
- check = true;
- }
- Thread t = new Thread(ServeClientConcurrently);
- t.Start(count-1);
- txt_QLKN.AppendText("Client " + (count ) + " connect" + "\n");
- }
- }
- public void ServeClientConcurrently(object obj)
- {
- //get correct socket
- int index = (Int32)obj;
- while (true)
- {
- byte[] b = new byte[100];
- //string temp = socket[index].RemoteEndPoint.ToString();
- try
- {
- int k = socket[index].Receive(b);
- }
- catch
- {
- socket[index].Close();
- isUsed[index] = 0;
- check = false;
- txt_QLKN.AppendText("Client " + (index + 1) + " disconnect" + "\n");
- return;
- }
- string abc = Encoding.ASCII.GetString(b);
- sum[index] = SumFun(abc);
- Txt_QLTV.AppendText("Yêu cầu từ client " + (index + 1).ToString() + "\n");
- Txt_QLTV.AppendText("Kết quả: " + sum[index] + "\n");
- ASCIIEncoding asen = new ASCIIEncoding();
- socket[index].Send(asen.GetBytes(sum[index]));
- }
- }
- public string SumFun(string str)
- {
- string[] strS = str.Split('/');
- int x1 = int.Parse(strS[0]);
- int x2 = int.Parse(strS[1]);
- int sum = x1 + x2;
- return sum.ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement