Having problems getting client socket code working in 5.4 that works fine in Unity4. Get the above error in 5.4.0b14 and “EnsureRunningOnMainThread can only be called from the main thread.” in b13. Code follows any suggestions very welcome.
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class AsynchClient : MonoBehaviour
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
public UITextList textList;
void Awake()
{
SetupServer();
}
private void SetupServer()
{
string host = "127.0.0.1";
int port = 8888;
IPHostEntry hostEntry = null;
hostEntry = Dns.GetHostEntry(host);
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
try
{
_clientSocket.Connect(ipe);
}
catch (SocketException ex)
{
Debug.Log(ex.Message);
}
if (_clientSocket.Connected)
{
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
break;
}
else
{
continue;
}
}
}
private void ReceiveCallback(IAsyncResult AR)
{
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = _clientSocket.EndReceive(AR);
if (recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);
//Process data here the way you want , all your bytes will be stored in recData
textList.Add(Encoding.ASCII.GetString(_recieveBuffer, 0, _recieveBuffer.Length));
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}