Skip to content

Instantly share code, notes, and snippets.

@jeffijoe
Created November 27, 2013 08:36
Show Gist options
  • Save jeffijoe/7672529 to your computer and use it in GitHub Desktop.
Save jeffijoe/7672529 to your computer and use it in GitHub Desktop.
/*
Authors: Jeff Hansen, Bjarke Søgaard
Description: Simple TCP Client for use in Unity3D. Very nice, so doge.
*/
public class SimpleTcpClient
{
private TcpClient socket;
private NetworkStream net_stream;
private StreamWriter socket_writer;
private StreamReader socket_reader;
private bool ready;
public string Read()
{
if (!ready) return string.Empty;
if (net_stream.DataAvailable)
return socket_reader.ReadLine();
return string.Empty;
}
public void Write(string data)
{
if (!ready) return;
socket_writer.WriteLine(data);
}
// Use this for initialization
public SimpleTcpClient(string host, int port)
{
try
{
socket = new TcpClient(host, port);
net_stream = socket.GetStream();
socket_writer = new StreamWriter(net_stream);
socket_writer.AutoFlush = true;
socket_reader = new StreamReader(net_stream);
ready = true;
}
catch (Exception e)
{
Console.WriteLine("Socket error: " + e);
}
}
~SimpleTcpClient()
{
if (!ready) return;
ready = false;
socket_reader.Close();
socket_writer.Close();
socket.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment