TcpListener没有';在不同设备上运行时,不接受TcpClient[C#,Unity]

TcpListener没有';在不同设备上运行时,不接受TcpClient[C#,Unity],c#,android,unity3d,networking,.net-core,C#,Android,Unity3d,Networking,.net Core,服务器代码(用.NET核心编写) 使用系统; 使用系统集合; Net系统; 使用System.Net.Sockets; 使用系统线程; 使用系统文本; 使用System.Xml; 使用System.Xml.Schema; 使用模型; 使用System.Collections.Generic; 使用Newtonsoft.Json; 使用记录器; 使用System.IO; 公共类服务器 { 私家侦探倾听; 专用int端口; 专用IP地址本地地址; 私人名单客户; 专用网络流; 专用记录器; 私人字典

服务器代码(用.NET核心编写)

使用系统;
使用系统集合;
Net系统;
使用System.Net.Sockets;
使用系统线程;
使用系统文本;
使用System.Xml;
使用System.Xml.Schema;
使用模型;
使用System.Collections.Generic;
使用Newtonsoft.Json;
使用记录器;
使用System.IO;
公共类服务器
{
私家侦探倾听;
专用int端口;
专用IP地址本地地址;
私人名单客户;
专用网络流;
专用记录器;
私人字典锁定播放器;
私有字符串响应;
私人布尔伊斯鲁米诺;
私人厕所是固定的;
/// 
///服务器构造函数
/// 
///用于创建服务器日志的对象
公用服务器(LoggerDevice日志)
{
端口=8000;
localAddress=IPAddress.Parse(GetLocalIPAddress());
侦听=新的TcpListener(本地地址、端口);
//侦听=新的TcpListener(IPAddress.Any,port);
IPEndPoint iep=listen.LocalEndpoint作为IPEndPoint;
//localAddress=iep.Address;
clients=新列表();
response=string.Empty;
记录器=日志;
lockedPlayers=新字典();
isLuminol=假;
isFixative=假;
}
/// 
///返回主机的本地IP地址
/// 
///主机的本地IP地址
公共静态字符串GetLocalIPAddress()
{
var host=Dns.GetHostEntryAsync(Dns.GetHostName());
Console.WriteLine(“DNS主机名:+DNS.GetHostName());
foreach(host.Result.AddressList中的var ip)
{
if(ip.AddressFamily==AddressFamily.InterNetwork)
{
返回ip.ToString();
}
}
抛出新异常(“未找到本地IP地址!”);
}
/// 
///主服务器线程方法
///显示当前IP地址并与客户端连接
/// 
public-void-ServThread()
{
response=“Adres IP serwera:”+((IPEndPoint)(listen.LocalEndpoint)).Address.ToString()+'\n';
控制台写入线(响应);
logger.WriteLine(响应);
客户端模型;
听。开始();
while(true)
{
Console.WriteLine(“Czekam na polaczenie…”);
currentClient=new ClientModel();
currentClient.clientSender=listen.AcceptTcpClientAsync().Result;
QueueUserWorkItem(HandleClient,currentClient);
}
}
/// 
///方法创建和配置ClientModel的新实例
///在需要时分配新的ClientModel.Id,并在重新连接时将ClientModel与分配的播放机匹配
/// 
///要处理的客户端(在方法中显式转换为ClientModel)
私有无效HandleClient(对象c)
{
ClientModel currentClient=(ClientModel)c;
回复=“Polaczono!”;
控制台写入线(响应);
logger.WriteLine(响应);
通信模型currentCommunication=新通信模型();
Random rand=新的Random();
字符串currentID;
if(string.IsNullOrEmpty(currentClient.Id))
{
Guid g=Guid.NewGuid();
currentID=g.ToString();
currentClient.Id=g.ToString();
response=“Nadano nowe ID:”+currentClient.ID;
控制台写入线(响应);
logger.WriteLine(响应);
clients.Add(currentClient);
}
currentID=currentClient.Id;
currentCommunication.Id=currentID;
IPEndPoint ipep=(IPEndPoint)currentClient.clientSender.Client.RemoteEndPoint;
IPAddress ipa=ipep.地址;
if(锁定玩家。容器(ipa))
{
CommunicationModel mess=新的CommunicationModel();
字符串currentId=currentClient.Id;
response=“Dolaczyl-gracz ze zwiazanym playerem(ID:+currentID+”);
控制台写入线(响应);
logger.WriteLine(响应);
currentClient.clientSender.GetStream();
currentClient.clientSender.GetStream().Flush();
Id=currentId;
mess.Message=JsonConvert.SerializeObject(LockedPlayer[ipa]);
类型=101;
字符串comMess=JsonConvert.SerializeObject(mess);
byte[]data=UTF8Encoding.UTF8.GetBytes(comMess);
currentClient.clientSender.GetStream().Write(数据,0,数据.Length);
response=“Pomyslnie przypisano gracza z ID:”+currentId+“do jego domyslnego playera”;
控制台写入线(响应);
logger.WriteLine(响应);
}
servMessReceived(clients.Find(x=>x.Id.Equals(currentID));
}
公共类项目模型
{
公共字符串名称=”;
公共利益;
}
ServThread是从其他脚本启动的

客户端代码(统一脚本)

使用系统;
Net系统;
使用System.Net.Sockets;
使用系统文本;
使用系统线程;
使用模型;
使用UnityEngine;
使用系统集合;
类客户端:单行为
{
tcpclientclientsocket;
通信模型;
i终点;
PlayerNetworkController播放器;
NetworkStream客户端流;
int state=0;
字节[]rec=新字节[100000];
整数字节;
布尔阅读;
私有void Start()
{
//clientSocket=新的TcpClient(AddressFamily.InterNetwork);
mess=新的通信模型();
player=IOC.Resolve(“GameManager”).playerNetworkController;
布尔读数=真;
}
私有void更新()
{
}
公共无效连接端(字符串ip)
{
结束=新的IPEndPoint(
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using Models;
using System.Collections.Generic;
using Newtonsoft.Json;
using Logger;
using System.IO;

public class Server
{
    private TcpListener listen;
    private int port;
    private IPAddress localAddress;
    private List<ClientModel> clients;
    private NetworkStream stream;
    private LoggerDevice logger;
    private Dictionary<IPAddress, PlayerModel> lockedPlayers;
    private string response;
    private bool isLuminol;
    private bool isFixative;

    /// <summary>
    /// Server constructor
    /// </summary>
    /// <param name="log">Object used to create server logs</param>
    public Server(LoggerDevice log)
    {
        port = 8000;
        localAddress = IPAddress.Parse(GetLocalIPAddress());
        listen = new TcpListener(localAddress, port);
        //listen = new TcpListener(IPAddress.Any, port);
        IPEndPoint iep = listen.LocalEndpoint as IPEndPoint;
        //localAddress = iep.Address;
        clients = new List<ClientModel>();

        response = string.Empty;
        logger = log;

        lockedPlayers = new Dictionary<IPAddress, PlayerModel>();

        isLuminol = false;
        isFixative = false;
    }


    /// <summary>
    /// Returns a local IP Address of the host
    /// </summary>
    /// <returns>Local IP Address of the host</returns>
    public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntryAsync(Dns.GetHostName());
        Console.WriteLine("DNS HOSTNAME: " + Dns.GetHostName());
        foreach (var ip in host.Result.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }

    /// <summary>
    /// Main server thread method
    /// Displays current IP Address and connects with clients
    /// </summary>
    public void ServThread()
    {
        response = "Adres IP serwera: " + ((IPEndPoint)(listen.LocalEndpoint)).Address.ToString() + '\n';
        Console.WriteLine(response);
        logger.WriteLine(response);

        ClientModel currentClient;

        listen.Start();

        while (true)
        {
            Console.WriteLine("Czekam na polaczenie...");
            currentClient = new ClientModel();

            currentClient.clientSender = listen.AcceptTcpClientAsync().Result;
            ThreadPool.QueueUserWorkItem(HandleClient, currentClient);
        }
    }

    /// <summary>
    /// Method creating and configuring a new instance of ClientModel
    /// Assigns new ClientModel.Id when needed and matches ClientModel with the assigned player if reconnecting
    /// </summary>
    /// <param name="c">Client to be handled (explicitly converted to ClientModel in the method)</param>
    private void HandleClient(object c)
    {
            ClientModel currentClient = (ClientModel)c;

            response = "Polaczono!";
            Console.WriteLine(response);
            logger.WriteLine(response);

            CommunicationModel currentCommunication = new CommunicationModel();
            Random rand = new Random();

            string currentID;
            if (string.IsNullOrEmpty(currentClient.Id))
            {
                Guid g = Guid.NewGuid();
                currentID = g.ToString();

                currentClient.Id = g.ToString();

                response = "Nadano nowe ID: " + currentClient.Id;
                Console.WriteLine(response);
                logger.WriteLine(response);
                clients.Add(currentClient);
            }
            currentID = currentClient.Id;

            currentCommunication.Id = currentID;

            IPEndPoint ipep = (IPEndPoint)currentClient.clientSender.Client.RemoteEndPoint;
            IPAddress ipa = ipep.Address;
            if (lockedPlayers.ContainsKey(ipa))
            {
                CommunicationModel mess = new CommunicationModel();
                string currentId = currentClient.Id;

                response = "Dolaczyl gracz ze zwiazanym playerem (ID: "+currentID+")";
                Console.WriteLine(response);
                logger.WriteLine(response);

                currentClient.clientSender.GetStream();
                currentClient.clientSender.GetStream().Flush();

                mess.Id = currentId;
                mess.Message = JsonConvert.SerializeObject(lockedPlayers[ipa]);

                mess.Type = 101;

                string comMess = JsonConvert.SerializeObject(mess);

                byte[] data = UTF8Encoding.UTF8.GetBytes(comMess);
                currentClient.clientSender.GetStream().Write(data, 0, data.Length);

                response = "Pomyslnie przypisano gracza z ID: "+currentId+"do jego domyslnego playera";
                Console.WriteLine(response);
                logger.WriteLine(response);
            }

            servMessReceived(clients.Find(x => x.Id.Equals(currentID)));
    }


public class ItemModel
{
    public string Name = "";
    public bool Have;
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Models;
using UnityEngine;
using System.Collections;

class Client : MonoBehaviour
{
    TcpClient clientSocket;
    CommunicationModel mess;
    IPEndPoint end;
    PlayerNetworkController player;

    NetworkStream clientStream;
    int state = 0;
    byte[] rec = new byte[100000];
    int bytes;

    bool reading;

    private void Start()
    {
        //clientSocket = new TcpClient(AddressFamily.InterNetwork);
        mess = new CommunicationModel();
        player = IOC.Resolve<WorshipGameManager>("WorshipGameManager").playerNetworkController;
        bool reading = true;
    }

    private void Update()
    {

    }

    public void ConnectEnd(string ip)
    {
        end = new IPEndPoint(IPAddress.Parse(ip), 8000);

        clientSocket = new TcpClient(AddressFamily.InterNetwork);
        clientSocket.Connect(end.Address, end.Port);

        clientStream = clientSocket.GetStream();
        StartCoroutine(ReceiveMessage());
    }

    private IEnumerator ReceiveMessage()
    {
        //Odczytywanie odpowiedzi
        //clientStream = clientSocket.GetStream();
        float timePassed = 0.0f;
        rec = new byte[100000];
        while (true)
        {
            if (timePassed > 5.0f)
                timePassed = 0.0f;
            timePassed += Time.deltaTime;

            clientStream.BeginRead(rec, 0, rec.Length, new AsyncCallback(this.HandleMessage), this);

            yield return new WaitWhile(() => reading == true || timePassed >= 5.0f);
        }

    }

    public void HandleMessage(IAsyncResult ar)
    {
        reading = true;
        bytes = clientStream.EndRead(ar);
        clientStream.Flush();
        if (bytes > 0)
        {
            string responseMessage = UTF8Encoding.UTF8.GetString(rec, 0, bytes);
            Debug.Log("Message received: " + responseMessage);


            CommunicationModel cm = JsonUtility.FromJson<CommunicationModel>(responseMessage);
            Debug.Log("cm.Name: " + cm.Name);
            Debug.Log("cm.Type: " + cm.Type);
            Debug.Log("cm.Id: " + cm.Id);
            Debug.Log("cm.Message: " + cm.Message);

            if (player == null)
                player = IOC.Resolve<WorshipGameManager>("WorshipGameManager").playerNetworkController;

            switch (cm.Type)
            {
                case 100:
                    player.OnConnectToServer(""); break;
                case 101:
                    player.GetPlayerData(cm); break;
                case 111:
                    player.GetItemFromServer(cm); break;
                case 112:
                    player.SetLuminolActive(cm); break;
                case 113:
                    player.SetItemFromServer(cm); break;
                case 114:
                    player.SetType(cm); break;
            }
        }
        reading = false;
    }
    public void SendMessageAsync(short type, string message)
    {
        {
            byte[] rec = new byte[100000];

            mess.Id = "0";
            mess.Type = type;
            mess.Message = message;

            rec = Encoding.ASCII.GetBytes(JsonUtility.ToJson(mess));

            NetworkStream clientStream = clientSocket.GetStream();

            clientStream.Write(rec, 0, rec.Length);
            clientStream.Flush();

            message = Console.ReadLine();
        }
    }

    public void OnServerConnect()
    {
        Debug.Log("OnServerConnect");
        player.OnConnectToServer("");
    }
}
port = 8000;
localAddress = IPAddress.Parse(GetLocalIPAddress());
listen = new TcpListener(localAddress, port);
port = 8000;
localAddress = IPAddress.Any;
listen = new TcpListener(localAddress, port);