我想做一个Ionic应用,每0.5秒发送一个小的json到unity(如果它能和控制台以及PC兼容就更好了).我想在ionic上使用一个socket.io客户端,在第一次测试中,我试着实现代码,并在浏览器上的一个简单的网页中运行它。
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js'></script>
<script>
var socket = io("127.0.0.1:8052");
socket.on('connect', function(data) {
console.log("Connected")
setInterval(function(){
console.log("Sending")
socket.emit({test: "testings"});
}, 1000);
});
socket.on('error', console.error.bind(console));
</script>
在unity方面,我找到了一个简单的tcp服务器的代码。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class Server : MonoBehaviour
{
private TcpListener tcpListener;
private Thread tcpListenerThread;
private TcpClient connectedTcpClient;
void Start()
{
// Start TcpServer background thread
tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
}
private void ListenForIncommingRequests()
{
try
{
// Create listener on localhost port 8052.
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8052);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
// Get a stream object for reading
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
// Read incomming stream into byte arrary.
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
// Convert byte array to string message.
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}
}
我把脚本分配给一个空对象,然后运行unity应用;然后我在wamp里打开带有socket.io脚本的html页面。在unity控制台,我可以看到日志说:
client message received as: GET /socket.io/?EIO=3&transport=polling&t=NB8a1dy HTTP/1.1
Host: 127.0.0.1:8052
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36
Origin: http://localhost
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost/test.html
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6,hu;q=0.5,ru;q=0.4
正如你所看到的,我试图从socket.io html页面发出的json对象没有任何内容,我甚至无法在该页面的console.log("Connected");信息中得到console.log("Connected"); console.How can I make my ionic app communicate with unity in a socket way?