I am writing a simple Tcp server in Unity and have my Flash application connects to it. I found a great tutorial on threaded Tcp server online, and my flash app connects to it nicely. However, I am not able to send data outside of the listening thread to the connected client. I tried to create a global reference of the Tcpclient obtained inside of the thread. However, that reference (sclient) only works inside of the listening thread, printed Null to console outside of the thread. There must be something I can do to retain the TCP client reference for later use or access it from outside of block thread. Please help!
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
public class TCPServer: MonoBehaviour
{
private TcpListener tcpListener;
private Thread listenThread;
private TcpClient sclient;
public float fireRate = 0.5F;
private float nextFire = 0.0F;
public TCPServer()
{
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
this.tcpListener = new TcpListener(localAddress, 9001);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
public void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
sclient = this.tcpListener.AcceptTcpClient();
print(sclient);//print "System.Net.Sockets.TcpClient" in console
this.sMessage("Can you hear me now?");//this one works fine
}
}
public void sMessage(String m){
print(cStream); //print "Null" to console
NetworkStream clientStream = sclient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(m);
print("Received Connection from " + tcpClient.Client.RemoteEndPoint );
print("Sending message..");
print(clientStream.CanWrite);//returns true in console
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.WriteByte (0);
clientStream.Flush();
}
void Update() {
if (Input.GetButton("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
this.sMessage("BOOM BOOM");//this one won't work. keep saying sclient is null
}
}