我正在 Unity 中编写一个简单的 Tcp 服务器,并让我的 Flash 应用程序连接到它。我在网上找到了一个关于线程 Tcp 服务器的很棒的教程,我的 flash 应用程序很好地连接到了它。但是,我无法将侦听线程之外的数据发送到连接的客户端。我试图创建线程内部获得的 Tcpclient 的全局引用。但是,该引用 (sclient) 仅在侦听线程内部有效,将 Null 打印到线程外部的控制台。我必须做一些事情来保留 TCP 客户端引用以供以后使用或从块线程外部访问它。请帮忙!
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
}
}