【问题标题】:Multiplayer doesn't work with other computers. Only on the same one多人游戏不适用于其他计算机。只在同一个
【发布时间】:2023-03-28 18:15:01
【问题描述】:

标题已经说了。我有一个 tcp 监听器,您可以使用 ipadress.any 访问它。但是当我在其他计算机上测试它时,我的连接不起作用。这是我的服务器代码:

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:

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

客户:

     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();
    }

这可能是一个非常简单的错误,但我不知道为什么当我在我的电脑上打开多个程序时它会起作用。但是在其他电脑上打开就不行了。

【问题讨论】:

  • 您的计算机是否运行了防火墙?

标签: c# tcp server client


【解决方案1】:

你有以下代码行:

Connection.Connect("localhost", port);

如果您尝试在另一台机器上执行此操作,它将在同一台机器上的请求端口上查找打开的套接字

【讨论】:

  • 这样的时刻让我质疑自己的存在。
  • 我也应该改变什么? :P 在我的辩护中,我不是专业程序员,只是一个刚起步的学生。初始服务器-客户端连接来自 github。我改变了很多,但我仍然不知道一切如何运作lol
  • 它需要是服务器运行的IP地址,最好在某个配置中。
  • 设置监听器的机器的 IP 地址或主机名
  • 您需要您的公共 IP 地址和服务器正在侦听的端口。设置好之后,您可能需要配置路由器防火墙以允许对该 ip:port 的收入请求。 (也可能来自 ip:port 的响应)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
相关资源
最近更新 更多