Hi all, I’m rookie, I’d like to ask for your help. Please.
I have the following code running on Windows in Unity Editor. (Reference links: http://kadri.synamicd.com/Unity/TCPConnection.cs)
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class TCPConnection : MonoBehaviour {
//the name of the connection, not required but better for overview if you have more than 1 connections running
public string conName = “Localhost”;
//ip/address of the server, 127.0.0.1 is for your own computer
public string conHost = “192.168.0.177”;
//port for the server, make sure to unblock this in your router firewall if you want to allow external connections
public int conPort = 843;
//a true/false variable for connection status
public bool socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
void Start(){
Security.PrefetchSocketPolicy (“localhost”, 843);
}
void Update(){
}
//try to initiate connection
public void setupSocket() {
try {
mySocket = new TcpClient(conHost, conPort);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e) {
Debug.Log(“Socket error:” + e);
}
}
//send message to server
public void writeSocket(byte[ ] SendBuffer) {
if (!socketReady)
return;
theStream.Write(SendBuffer, 0, SendBuffer.Length);
theWriter.Flush();
}
//read message from server
public string readSocket() {
String result = “”;
if (theStream.DataAvailable) {
Byte[ ] inStream = new Byte[mySocket.SendBufferSize];
theStream.Read(inStream, 0, inStream.Length);
result = inStream[0].ToString();
}
return result;
}
//disconnect from the socket
public void closeSocket() {
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}
//keep connection alive, reconnect if connection lost
public void maintainConnection(){
if(!theStream.CanRead) {
setupSocket();
}
}
}
When running the program, reported error. Here’s a message:
Socket error:System.Security.SecurityException: Unable to connect, as no valid crossdomain policy was found
at System.Net.Sockets.Socket.Connect_internal (IntPtr sock, System.Net.SocketAddress sa, System.Int32& error, Boolean requireSocketPolicyFile) [0x00000] in :0
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in :0
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in :0
at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in :0
at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[ ] ipAddresses, Int32 port) [0x00000] in :0
UnityEngine.Debug:Log(Object)
TCPConnection:setupSocket() (at Assets/Scripts/TCPconnection.cs:38)
socketScript:OnGUI() (at Assets/Scripts/socketScript.cs:50)