1

我正在 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
    }
}
4

2 回答 2

0

调用的方法在哪里Update

当您调用它时,听起来还没有连接客户端。

于 2012-02-16T06:34:37.177 回答
0

一般来说,如果你避免socket,networkstream的同步方法,你应该使用xxxxAsync(socket有这样的方法)或BeginXXX方法。这为您提供了连接客户端数量的高性能。好的,现在关于同步......您应该为每个新连接的客户端创建新线程并在该线程上开始会话处理。我建议您为连接的客户端创建一些会话类,并在该类中进行所有处理。

public class Your_Session
{
    private TcpClient m_pClient = null;

    public Your_Session(TcpClient client)
    {
        mpClient = client; // Assign client to mpClient
    }

    internal void Start(Object state)
    {
        // NOTE: call this Start method: 
        // ThreadPool.QueueUserWorkItem(new WaitCallback(session.Start));


        // Start your session processing here. This method is called from threapool thread. 
    }
}

只需在 ListenForClients 方法中调用 create session class instance(Your_Session session = new YourSession ...) 并调用 ThreadPool.QueueUserWorkItem(new WaitCallback(session.Start)); 开始会话处理。

于 2011-11-12T07:38:25.607 回答