TCP SocketServer可以工作,但不能在主线程(Unity)上执行

时间:2017-02-02 21:23:06

标签: c# multithreading unity3d thread-safety

我已成功减少了另一个TCP套接字服务器示例并确认它可以正常工作。我可以在Unity控制台中看到我的连接消息。但是,我认为由于线程问题,我无法在主应用程序中实现此问题。

如何修改以下内容,以便Update1的内容可以与我的主Unity应用程序通信?我试图实现UnityThread解决方案,但它只是挂起我的编辑器!

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;
using System;
using System.Threading;

public class TCPServer2 : MonoBehaviour {

  public bool isConnection, senddata1, senddata2, valuechanged, valuechanged2;

  public Thread mThread;
  public TcpListener server;
  public TcpClient client;
  public NetworkStream stream;
  byte[] msg1;
  string toSend;
  bool available,  selection, endpointChanged, parsedata;
  public String data, prevdata;
  int q = 0;
  int FPS = 0;

  // Use this for initialization
  void Start () {
  UnityThread.initUnityThread();
  isConnection = false;
  senddata1 = false;
  senddata2 = false;
  //print ("StartThread");
  ThreadStart ts = new ThreadStart(Update1);
  mThread = new Thread(ts);
  mThread.Start();
  }

  void Update()
  {

  }

  void Update1()
  {
  server = null;
  try
  {
  Int32 port = 1234;
  server = new TcpListener(IPAddress.Any, port);

  // Start listening for client requests.
  server.Start();

  // Buffer for reading data
  Byte[] bytes = new Byte[256];
  String data = null;

  // Enter the listening loop.
  while (true)
  {
  Thread.Sleep(10);

  Debug.Log("Waiting for a connection... ");

  client = server.AcceptTcpClient();
  if (client != null)
  {

  Debug.Log("Connected!");

  }
  data = null;

  // Get a stream object for reading and writing
  stream = client.GetStream();
  //StreamWriter swriter = new StreamWriter(stream);
  int i;

  // Loop to receive all the data sent by the client.
  while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)

  {
  data = Encoding.ASCII.GetString(bytes, 0, i);
  Debug.Log("0 ASSERT Received: data = " + data);

  switch (data)
  {
  case "TRIGGER":
  Debug.Log(":::::::::::::::1 ASSERT TRIGGER RECEIVED");

  /*
  toSend = "RECEIVED";

  msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
  stream.Write(msg1, 0, msg1.Length);
  */
  //stream.Flush();
  break;
  case "Disconnect":
  goto q;

  default:
  prevdata = "RECEIVED_NO_TRIGGER";
  byte[] msg = System.Text.Encoding.ASCII.GetBytes(prevdata);

  // Send back a response.
  stream.Write(msg, 0, msg.Length);

  break;
  }
  }
  q:
  // Shutdown and end connection
  client.Close();
  }

  }
  catch (SocketException e)
  {
  Debug.LogError("SocketException:" + e);
  }
  finally
  {
  // Stop listening for new clients.
  server.Stop();
  }

  }
  void OnApplicationQuit()
  {
  server.Stop();
  mThread.Abort();
  }
}

0 个答案:

没有答案