viewing paste Unknown #373 | C#

Posted on the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
 
namespace Sensecontrol_Server
{
    public partial class Server : Form
    {
        private TcpListener tcpListener;
        private Thread listenThread;
 
        public Server()
        {
            InitializeComponent();
            this.tcpListener = new TcpListener(IPAddress.Any, 1727);
            ListenForClients();
        }
 
        private void ListenForClients()
        {
            this.tcpListener.Start();
 
            while (true)
            {
                //blocks until a client has connected to the server
                client_connected.Checked = true;
                text_test.Text = "Klient EJ ansluten";
                TcpClient client = this.tcpListener.AcceptTcpClient();
                text_test.Text = "Klient har anslutits";
 
                //create a thread to handle communication 
                //with connected client
                HandleClientComm(client);
            }
        }
 
        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
 
            byte[] message = new byte[4096];
            int bytesRead;
 
            while (true)
            {
                bytesRead = 0;
 
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                    client_connected.Checked = true;
                }
                catch
                {
                    //a socket error has occured
                    break;
                }
 
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    client_connected.Checked = false;
                    break;
                }
 
                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
 
                //sätt text
                text_test.Text = message.ToString();
            }
 
            tcpClient.Close();
        }
 
        private void text_test_TextChanged(object sender, EventArgs e)
        {
 
        }
 
    }
}
Viewed 818 times, submitted by Guest.