使用C#的多线程游戏服务器

时间:2017-09-09 18:00:12

标签: c# multithreading server

我对此非常陌生,并希望为局域网游戏配置C#服务器提供一些帮助。服务器需要将对象发送到连接到服务器的所有客户端,然后等待其响应。在所有玩家回应之后,服务器向所有参与者宣布获胜者并生成新游戏(在获胜者宣布之后我等待大约5秒钟以生成下一个游戏)

我无法通过NetworkStream发送该对象

服务器端:

public static void broadcast(string uName, bool flag)
    {
        game.Generate();
        foreach (Client Item in clientsList)
        {
            TcpClient broadcastSocket;
            broadcastSocket = (TcpClient)Item.clientSocket;
            NetworkStream broadcastStream = broadcastSocket.GetStream();
            Byte[] broadcastBytes = null;

            if (flag == true)
            {
                broadcastBytes = Encoding.ASCII.GetBytes("Winner is " + uName);
            }
            else
            {

                broadcastBytes = ToByteArray(game);

            }

            broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
            broadcastStream.Flush();
        }
    }

    public static byte[] ToByteArray(Game24 obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }

客户方:

private void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            try
            {
                GenerateGame(inStream);
                isGame = true;   // testing
            }
            catch(Exception ex) {
                MessageBox.Show("No object");
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
            }

            if (isGame)
                MessageBox.Show("Works  " + readData);

        }
    }

    private Game24 deserializeData(byte[] arr) {

        IFormatter br = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(arr))
        {
            object obj = br.Deserialize(ms);
            return (Game24)obj;
        }
    }

    private void GenerateGame(byte[] arrBytes)
    {

        game = deserializeData(arrBytes);
        Generate();

            MessageBox.Show("Test2");
            timer1.Start();
            timer2.Start();

    }

它始终显示“无对象”消息

0 个答案:

没有答案