Unity で単純な Tcp サーバーを作成しており、Flash アプリケーションをそれに接続しています。スレッド化された Tcp サーバーに関する優れたチュートリアルをオンラインで見つけました。私のフラッシュ アプリはそれにうまく接続します。ただし、リスニング スレッドの外部にあるデータを接続されたクライアントに送信することはできません。スレッド内で取得した 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
}
}