Я создал этот скрипт, который получает запросы API из сети и выполняет некоторые действия в игре.
Код: Выделить всё
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
public class NetworkAPIManager : MonoBehaviour
{
private HttpListener listener;
private Thread listenerThread;
void Start()
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:7000/");
listener.Prefixes.Add("http://127.0.0.1:7000/");
string ip = GetIP(ADDRESSFAM.IPv4);
Debug.Log(ip);
listener.Prefixes.Add("http://" + ip + ":7000/");
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Start();
listenerThread = new Thread(startListener);
listenerThread.Start();
Debug.Log("Server Started");
}
private string GetIP(ADDRESSFAM Addfam)
{
//Return null if ADDRESSFAM is Ipv6 but Os does not support it
if (Addfam == ADDRESSFAM.IPv6 && !Socket.OSSupportsIPv6)
{
return null;
}
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
#endif
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
//IPv4
if (Addfam == ADDRESSFAM.IPv4)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
//IPv6
else if (Addfam == ADDRESSFAM.IPv6)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
output = ip.Address.ToString();
}
}
}
}
}
return output;
}
private void OnDestroy()
{
if (listener != null && listener.IsListening)
{
listener.Stop();
listener.Close();
listenerThread.Abort();
Debug.Log("Server Stopped");
}
}
private void startListener()
{
while (true)
{
try
{
var result = listener.BeginGetContext(ListenerCallback, listener);
result.AsyncWaitHandle.WaitOne();
}
catch (Exception e) {
Debug.Log(e);
}
}
}
private void ListenerCallback(IAsyncResult result)
{
var context = listener.EndGetContext(result);
if (context.Request.HttpMethod == "GET")
{
string responseString = GetResponseBasedOnParameters(context.Request.QueryString);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
context.Response.ContentLength64 = buffer.Length;
Stream output = context.Response.OutputStream;
output.Write(buffer, 0, buffer.Length);
}
else if (context.Request.HttpMethod == "POST")
{
var data_text = new StreamReader(context.Request.InputStream,
context.Request.ContentEncoding).ReadToEnd();
Debug.Log($"Message received: {data_text}");
JObject data = JObject.Parse(data_text);
ActuatePostAPI(data);
}
context.Response.Close();
}
private void ActuatePostAPI(JObject data)
{
//apply code
}
private string GetResponseBasedOnParameters(System.Collections.Specialized.NameValueCollection parameters)
{
//apply code
}
}
public enum APIRequest
{
UpdateState, UpdatePosition, UpdateMap, PlayAudio, SetAlert
}
public enum ADDRESSFAM
{
IPv4, IPv6
}
Есть ли способ включить внешнее подключение к моему приложению, чтобы я мог получать сообщения с другого смартфона? Я пытался вставить адрес 0.0.0.0, что в принципе должно означать «Любое входящее соединение», которое на ПК работает, но после запуска приложения отладчик показывает эту ошибку: «SocketException: адрес уже используется»
Большое спасибо
Подробнее здесь: https://stackoverflow.com/questions/798 ... tplistener
Мобильная версия