将数据从c# TCP服务器发送到侦听线程之外的连接客户端

本文关键字:线程 客户端 连接 数据 TCP 服务器 | 更新日期: 2023-09-27 18:14:10

我正在Unity中编写一个简单的Tcp服务器,并将我的Flash应用程序连接到它。我在网上找到了一个关于线程Tcp服务器的教程,我的flash应用程序可以很好地连接到它。但是,我不能在侦听线程之外向连接的客户机发送数据。我尝试创建线程内部获得的Tcpclient的全局引用。但是,该引用(client)只在侦听线程内部工作,并将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
    }
}

将数据从c# TCP服务器发送到侦听线程之外的连接客户端

调用Update的方法在哪里?

当你调用它的时候,听起来好像还没有客户端连接。

一般来说,如果你避免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(新WaitCallback (session.Start));启动会话处理。