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)
{
}
}
}