我制作了一个简单的套接字服务器脚本和一个客户端脚本。
如果我在同一个项目中运行这两个脚本没有问题,但如果我从 Unity3D 游戏引擎运行客户端脚本,则没有连接并且控制台说我需要跨域策略。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SocketServer
{
class Program
{
static byte[] Buffer { get; set; }
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 5111));
sck.Listen(100);
Socket accepted = sck.Accept();
Buffer = new Byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
Console.Read();
sck.Close();
accepted.Close();
}
}
}