|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
|
using System.Net;
|
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
|
|
namespace MachineServer
|
|
|
|
|
|
{
|
|
|
|
|
|
internal class Server
|
|
|
|
|
|
{
|
|
|
|
|
|
TcpListener _server = null;
|
|
|
|
|
|
|
|
|
|
|
|
public Server(string ip, int port)
|
|
|
|
|
|
{
|
|
|
|
|
|
IPAddress localAddr = IPAddress.Parse(ip);
|
|
|
|
|
|
_server = new TcpListener(localAddr, port);
|
|
|
|
|
|
_server.Start();
|
|
|
|
|
|
StartListener();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private void StartListener()
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
while (true)
|
|
|
|
|
|
{
|
|
|
|
|
|
Console.WriteLine("Waiting for a connection...");
|
|
|
|
|
|
TcpClient client = _server.AcceptTcpClient();
|
|
|
|
|
|
Console.WriteLine("Connected!");
|
|
|
|
|
|
|
|
|
|
|
|
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
|
|
|
|
|
|
t.Start(client);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (SocketException e)
|
|
|
|
|
|
{
|
|
|
|
|
|
Console.WriteLine("SocketException: {0}", e);
|
|
|
|
|
|
_server.Stop();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public void HandleClient(object obj)
|
|
|
|
|
|
{
|
|
|
|
|
|
TcpClient client = (TcpClient)obj;
|
|
|
|
|
|
var stream = client.GetStream();
|
|
|
|
|
|
|
|
|
|
|
|
string imei = String.Empty;
|
|
|
|
|
|
|
|
|
|
|
|
string data = String.Empty;
|
|
|
|
|
|
|
|
|
|
|
|
Byte[] bytes = new Byte[256];
|
|
|
|
|
|
int i;
|
|
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
|
|
|
|
|
|
{
|
|
|
|
|
|
string hex = BitConverter.ToString(bytes);
|
|
|
|
|
|
//
|
|
|
|
|
|
int msgType = BitConverter.ToInt32(bytes, 0);
|
|
|
|
|
|
int msgLength = BitConverter.ToInt32(bytes, sizeof(int));
|
|
|
|
|
|
string msg = Encoding.ASCII.GetString(bytes, 2*sizeof(int), msgLength);
|
|
|
|
|
|
data = Encoding.ASCII.GetString(bytes, 0, i);
|
|
|
|
|
|
Console.WriteLine($"{data}: Received: {Thread.CurrentThread.ManagedThreadId}");
|
|
|
|
|
|
|
|
|
|
|
|
string str = "Hey Client!";
|
|
|
|
|
|
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
|
|
|
|
|
|
stream.Write(reply, 0, reply.Length);
|
|
|
|
|
|
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: Sent: {str}");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
|
{
|
|
|
|
|
|
Console.WriteLine("Exception: {0}", e.ToString());
|
|
|
|
|
|
client.Close();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|