Skip to content

Instantly share code, notes, and snippets.

@rob5300
Created April 8, 2018 11:07
Show Gist options
  • Save rob5300/e9d0cb4d0752188bab315ca4789e70d8 to your computer and use it in GitHub Desktop.
Save rob5300/e9d0cb4d0752188bab315ca4789e70d8 to your computer and use it in GitHub Desktop.
namespace AccelerometerServer
{
public class Server
{
public int Port;
public bool HasClient = false;
private Socket listener;
private Socket handler;
private string data = null;
public Server(int port)
{
Port = port;
}
public void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
// Program is suspended while waiting for an incoming connection.
handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
HasClient = true;
break;
}
}
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void Send(string data)
{
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment