将数据从C#TCP服务器打磨到侦听线程外部的连接客户端

时间:2011-11-12 05:34:53

标签: c# flash unity3d tcpclient tcpserver

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

2 个答案:

答案 0 :(得分:0)

一般情况下,如果你避免套接字,网络流的同步方法,你应该使用xxxxAsync(套接字有这样的方法)或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类实例(Your_Session session = new YourSession ...)并调用ThreadPool.QueueUserWorkItem(new WaitCallback(session.Start));开始会话处理。

答案 1 :(得分:0)

调用Update的方法在哪里?

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