Skip to content

Instantly share code, notes, and snippets.

@sdumetz
Last active November 3, 2021 08:46
Show Gist options
  • Save sdumetz/ca490544f200c7b2a92f to your computer and use it in GitHub Desktop.
Save sdumetz/ca490544f200c7b2a92f to your computer and use it in GitHub Desktop.
unity3D TcpListener example
public class UnityListener{
public UnityListener(){
tcpClientConnected = new ManualResetEvent(false);
server = new TcpListener(IPAddress.Parse("127.0.0.1"),8080);
server.Start();
// Set the event to nonsignaled state.
tcpClientConnected.Reset();
Debug.Log("Waiting for a connection...");
server.BeginAcceptTcpClient(
new AsyncCallback(DoAcceptTcpClientCallback), server);
// Wait until a connection is made and processed before
// continuing.
//tcpClientConnected.WaitOne();
}
public static void DoAcceptTcpClientCallback(IAsyncResult ar) {
string completeMessage = "";
ClientData cli = new ClientData();
// Get the listener that handles the client request.
TcpListener listener = (TcpListener) ar.AsyncState;
// End the operation and display the received data on
// the console.
cli.Client = listener.EndAcceptTcpClient(ar);
NetworkStream stream = cli.Client.GetStream();
if(stream.CanRead){
stream.BeginRead(cli.data, 0, cli.data.Length,
new AsyncCallback(ReadCallBack),
cli);
}
Debug.Log("Client connected");
// Signal the calling thread to continue.
tcpClientConnected.Set();
listener.BeginAcceptTcpClient(
new AsyncCallback(DoAcceptTcpClientCallback), listener);
}
public static void ReadCallBack(IAsyncResult ar ){
ClientData cli = (ClientData)ar.AsyncState;
NetworkStream stream = cli.Client.GetStream();
int bytesCount = stream.EndRead(ar);
cli.message = String.Concat(cli.message, Encoding.ASCII.GetString(cli.data, 0, bytesCount));
// message received may be larger than buffer size so loop through until you have it all.
if(stream.DataAvailable){
Debug.Log("data available");
stream.BeginRead(cli.data, 0, cli.data.Length,
new AsyncCallback(ReadCallBack),
stream);
}
// Print out the received message to the console.
Debug.Log("You received the following message : " +
cli.message);
}
}
@ykeremk
Copy link

ykeremk commented Sep 16, 2015

sorry How to use it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment