简体   繁体   English

多人游戏不适用于其他计算机。 只在同一个

[英]Multiplayer doesn't work with other computers. Only on the same one

The title says it already. 标题已经说过了。 I have a tcp listener and you can access it with ipadress.any. 我有一个TCP侦听器,您可以使用ipadress.any访问它。 But when i test it on other computers my connection doesn't work. 但是,当我在其他计算机上对其进行测试时,我的连接无法正常工作。 Here is my server code: 这是我的服务器代码:

namespace AsyncClientServer
{


public class Server
{
    public TcpListener Listener;
    private volatile bool Running; //wordt gebruikt door meerdere threads zonder lock te gebruiken (lock zorgt ervoor dat een thread niet doorgaat naar belangrijke code terwjil een andere thread nog bezig is om naar de locked code te gaan.
    private List<BinaryWriter> writers = new List<BinaryWriter>();
    bool playerCount = false;
    public Server(int port)
    {
        Listener = new TcpListener(IPAddress.Any, port);
    }

    public void Start()
    {
        Listener.Start(10);
        Running = true;

        while (Running)
        {
            var connection = Listener.AcceptTcpClient();
            ProcessConnection(connection);
        }
    }


    public async Task ProcessConnection(TcpClient connection)
    { 
        var writer = new BinaryWriter(connection.GetStream());

        lock (writers)
        {
            writers.Add(writer);
        }

        using (var stream = new BinaryReader(connection.GetStream()))
        {
            //hvlheid connectie
            await Task.Factory.StartNew(() => {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(writers.Count));
                playerCount = true;
                ProcessCommand(connection, writer, data);
            });
            //loop 
            while (Running && connection.Connected)
            {
                await Task.Factory.StartNew(() => {
                    var count = stream.ReadInt32();
                    var data = stream.ReadBytes(count);
                    ProcessCommand(connection, writer, data);
                });
            }
            connection.Close();
        }
        lock (writers)
        {
            writers.Remove(writer);
        }
    }


    private void ProcessCommand(TcpClient connection, BinaryWriter writer, byte[] data)
    {
        //var info = connection.Client.RemoteEndPoint as IPEndPoint;
        if (playerCount)
        {
            playerCount = false;
            lock (writers)
            {
                foreach (var w in writers)
                {
                    if (w != null)
                    {
                        try
                        {
                            w.Write((Int32)data.Length);
                            w.Write(data);
                            w.Flush();
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }
        else
        {
            //var line = System.Text.Encoding.UTF8.GetString(data);
            //var response = String.Format("{1}:{2}: {0}", line, info.Address.ToString(), info.Port);
            //Console.WriteLine(response);
            lock (writers)
            {
                foreach (var w in writers)
                {
                    if (w != null)
                    {
                        try
                        {
                            w.Write((Int32)data.Length);
                            w.Write(data);
                            w.Flush();
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }
    }


    public void Stop()
    {
        Running = false;
        Listener.Stop();
    }
    ~Server()
    {
        Running = false;
        Listener.Stop();
    }
}

} }

program.cs: program.cs:

     public static class MainClass
    {
        public static readonly int Port = 5000;
        public static void Main(string[] args)
        {
            var server = new Server(Port);
            server.Start();
        }
    }

Client: 客户:

     Start(5000);
 public async Task Start(int port)
    {

        Connection.Connect("localhost", port);
        Console.WriteLine("Connected");
        Running = true;
        Writer = new BinaryWriter(Connection.GetStream());

        using (var stream = new BinaryReader(Connection.GetStream()))
        {
            //infinite loop
            while (Running && Connection.Connected)
            {
                await Task.Factory.StartNew(() => {
                    var count = stream.ReadInt32();
                    var data = stream.ReadBytes(count);
                    ProcessCommand(data);
                });
            }
            Stop();
        }
    }
    //send player coordinates naar server
    int[] temporary = new int[4];

    public async Task Coordinates()
    {
        if (Client1)
        {
            temporary[0] = (int)Player1_x;
            temporary[1] = (int)Player1_y;
        }
        else
        {
            temporary[2] = (int)Player2_x;
            temporary[3] = (int)Player2_y;
        }
            await Task.Factory.StartNew(() =>
            {
                //send player 1 coordinates naar server
                var player_coordinates = new byte[temporary.Length * sizeof(int) + sizeof(bool) + sizeof(bool)];
                //zet coordinates in de byte array
                Buffer.BlockCopy(temporary, 0, player_coordinates, 0, temporary.Length * sizeof(int));
                //zet collision in de byte array
                Buffer.BlockCopy(BitConverter.GetBytes(Collision_player1), 0, player_coordinates, temporary.Length * sizeof(int), sizeof(bool));
                Buffer.BlockCopy(BitConverter.GetBytes(Collision_player2), 0, player_coordinates, temporary.Length * sizeof(int) + sizeof(bool), sizeof(bool));
                Writer.Write((Int32)player_coordinates.Length);
                Writer.Write(player_coordinates);
                Writer.Flush();
            });
    }
    //send data voor chat
    public async Task Send(String line)
    {
        if (Writer == null)
            return;
        await Task.Factory.StartNew(() => {
            var data = System.Text.Encoding.UTF8.GetBytes(line);
            Writer.Write((Int32)data.Length);
            Writer.Write(data);
            Writer.Flush();
        });
    }

    //krijg het aantal spelers connected
    private void ProcessCommand(byte[] data)
    {
        if (players)
        {
            var playerCount = System.Text.Encoding.UTF8.GetString(data);
            PlayerCountMethod(Convert.ToInt32(playerCount));
            if (playerCount == "1") {
                Client1 = true;
            }
            else if (playerCount == "2")
            {
                players = false;
            }

        } else
        {
            if (Client1)
            {
                Player2_x = BitConverter.ToInt32(data, 2 * sizeof(int));
                Player2_y = BitConverter.ToInt32(data, 3 * sizeof(int));
            } else
            {
                Player1_x = BitConverter.ToInt32(data, 0);
                Player1_y = BitConverter.ToInt32(data, sizeof(int));
            }
            //
            if (Collision_player1 == false)
            {
                Collision_player1 = BitConverter.ToBoolean(data, temporary.Length * sizeof(int));
            }
            //
            if (Collision_player2 == false)
            {
                Collision_player2 = BitConverter.ToBoolean(data, temporary.Length * sizeof(int) + sizeof(bool));
            }

            //try-catch want anders argument out of range als er geen message wordt gestuurd
            //try
            //{
            //    var line = BitConverter.ToString(data, temporary.Length * sizeof(int));
            //    ////stuur data van server naar method
            //    textboxChat(line);
            //}
            //catch
            //{

            //}
        }

    }


    public void Stop()
    {
        Running = false;
        Writer.Close();
        Writer = null;
        Connection.Close();

    }
    ~GamePlay()
    {
        Stop();
    }

Its probably a realy easy mistake, but i don't know why it works when i open multiple program's on my pc. 这可能是一个非常容易的错误,但是当我在PC上打开多个程序时,我不知道为什么它会起作用。 But it doesn't work when i open it on other pc's. 但是当我在其他PC上打开它时,它不起作用。

You have the following line of code: 您具有以下代码行:

Connection.Connect("localhost", port);

If you try to execute this on another machine it will look for an open socket on the request port on the same machine 如果尝试在另一台计算机上执行此操作,它将在同一计算机上的请求端口寻找打开的套接字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WPF应用程序无法在其他计算机上运行 - WPF application doesn't work in other computers C#应用程序无法在其他计算机上运行 - C# app doesn't work in other computers 安装后,带有 Access 数据库 (accdb) 的 c# windows 应用程序在其他计算机上不起作用 - The c# windows app with Access database (accdb) doesn't work on other computers after installation 我将 c# windows 应用程序与 Access 数据库 (accdb) 连接,但该应用程序在其他计算机上不起作用 - I connected c# windows app with Access database (accdb) but the application doesn't work on other computers 在关闭防火墙的同一子网上的两台计算机之间,WCF发现不起作用 - WCF discovery doesn't work between two computers on the same subnet with the firewall turned off Microsoft UIAutomation始终不能在某些计算机上运行。 C# - Microsoft UIAutomation isn't ALWAYS working on some computers. C# 为什么这个LINQ连接查询工作,但另一个没有? - Why does this LINQ join query work, but this other one doesn't? 转换器不想只在一种情况下工作 - Converter Doesn't want to work in only one situation Unity Multiplayer:Camera仅跟随一名玩家 - Unity Multiplayer:Camera Only following one player 我在一个解决方案中有 2 个项目。 一个 dockerfile 可以工作,另一个不可以 - I have 2 projects in one solution. One dockerfile does work the other doesn't
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM