我正在Unity中編寫一個簡單的Tcp服務器,並讓我的Flash應用程序連接到它。我在線上的Tcp服務器上找到了一個很好的教程,我的Flash應用程序很好地連接到它。但是,我無法將偵聽線程之外的數據發送到連接的客戶端。我試圖創建一個在線程內部獲得的Tcpclient的全局引用。但是,該引用(sclient)只能在偵聽線程內部工作,在線程之外打印Null以進行控制檯。我必須做些事情來保留TCP客戶端引用以供以後使用或從塊線程之外訪問它。請幫忙!從C#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
}
}
嗨伊瓦爾感謝您的解決方案我會給它一個鏡頭,我有0線程/會話編程的經驗。在我一秒鐘進入之前,一旦我開始會話,我該如何向客戶端發送數據?例如,我有一個不斷更新併發送給客戶端的外部值,我如何在此會話中執行此操作? – Ghettokon
我不明白你的意思。 – Ivar