Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net;
- using System.Windows.Forms;
- using System.Threading;
- using System.Text.RegularExpressions;
- namespace Fserver
- {
- class Conexion
- {
- private TcpClient client;
- private TcpListener listener;
- private Dictionary<TcpClient, int> list = new Dictionary<TcpClient, int>();
- private int initId = 0;
- private Label updateUsers = new Label();
- private ListBox updateUserList = new ListBox();
- private RichTextBox updateLogs = new RichTextBox();
- public bool allowConexions = true;
- public void Start(Label lb , ListBox list,RichTextBox txt)
- {
- this.listener = new TcpListener(IPAddress.Any, 4000);
- this.listener.Start();
- this.updateUsers = lb;
- this.updateUserList = list;
- this.updateLogs = txt;
- while (allowConexions && this.list.Count < 100)
- {
- this.client = this.listener.AcceptTcpClient();
- this.handleClient(this.client, initId);
- }
- txt.Text += "\n Conexion denied";
- }
- private void handleClient(TcpClient c,int id)
- {
- this.initId++;
- this.updateUsers.Text = this.list.Count().ToString();
- this.updateUserList.Items.Add("ClientId:" + this.initId.ToString());
- this.list.Add(c, id);
- new Thread(() => startRead(c,id)).Start();
- }
- private void startRead(TcpClient client,int id)
- {
- NetworkStream stream = client.GetStream();
- while (client.Connected)
- {
- try
- {
- byte[] buffer = new byte[client.Available];
- stream.Read(buffer, 0, buffer.Length);
- this.handleData(int.Parse(this.parsePacket(0, buffer)), this.parsePacket(1, buffer));
- this.updateLogs.Text += "\n Client sent: " + Encoding.Default.GetString(buffer);
- stream.Flush();
- }
- catch
- {
- this.updateLogs.Text += "\n Error reading client,closing..";
- stream.Flush();
- stream.Close();
- client.Close();
- }
- Thread.Sleep(1);
- }
- this.initId--;
- this.updateUserList.Items.Remove("ClientId:" + id.ToString());
- this.list.Remove(client);
- this.updateUsers.Text = this.initId.ToString();
- this.updateLogs.Text += "\n Client closed";
- }
- private void handleData(int id, string body)
- {
- switch (id)
- {
- case 0:
- break;
- }
- }
- private string parsePacket(int param, byte[] buffer)
- {
- return Regex.Split(Encoding.Default.GetString(buffer), "|")[param];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement