C#基於TCP實現簡單遊戲客戶端的完整實例

一、界面

左上方播放音頻按鈕和停止播放下面是圖片展示再下面是進入遊戲以及退出遊戲最後是命令輸入框右邊是消息框

二、代碼

1.播放音頻

需要用到WindowsMediaPlayer組件,在常規組件的選擇項裡面可以找到。

實現代碼

		private void start_Click(object sender, EventArgs e)
        {
            //新建線程打開音頻文件
            new Thread(new ThreadStart(beginPlay)).Start();
        }

        private void stop_Click(object sender, EventArgs e)
        {
            //暫定播放
            axWindowsMediaPlayer1.Ctlcontrols.pause();
        }
 		public void beginPlay()
        {
            string s = @"G:\VisualStudioProject\GameWindows\resources\music.mp3";
            axWindowsMediaPlayer1.URL = s;
        }

2.播放圖片

使用定時器,使能並且設置每1000ms觸發一次事件

事件函數

        private String[] pictures={ "\\1.jpg", "\\2.jpg","\\3.jpg","\\4.jpg","5.jpg","6.jpg"};
        private int postion = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile("G:\\VisualStudioProject\\GameWindows\\resources\\"+pictures[(++postion)%pictures.Length]);
        }

3.登錄和退出遊戲

采用tcp協議和服務器建立連接

public void connection()
        {
            try
            {
                //向指定的IP地址的服務器發出連接請求

                tcpClient.Connect("10.1.230.74", 3900);
                messages.Items.Add("連接成功!");
                stream = tcpClient.GetStream();
                byte[] data = new byte[1024];
                //判斷網絡流是否可讀            
                if (stream.CanRead)
                {
                    int len = stream.Read(data, 0, data.Length);
                    string msg = Encoding.Default.GetString(data, 0, data.Length);
                    string str = "\r\n";
                    char[] str1 = str.ToCharArray();
                    string[] msg1 = msg.Split(str1);
                    for (int j = 0; j < msg1.Length; j++)
                    {
                        messages.Items.Add(msg1[j]);
                    }
                }

            }
            catch (System.Exception ex)
            {
                messages.Items.Add(ex.Message);
            }
        }

登錄遊戲建立tcp連接,並且禁用登錄按鈕使能退出按鈕退出遊戲則端口tcp連接,並且禁用退出按鈕以及使能登錄按鈕

private void quitGame_Click(object sender, EventArgs e)
        {
            tcpClient.Close();
            beginGame.Enabled = true;
            quitGame.Enabled = false;
        }

4.命令交互

通過tcp向服務器發送數據

        private void sendButton_Click(object sender, EventArgs e)
        {
            sendCommand();
        }
		public void sendCommand()
        {
            if (tcpClient.Connected)
            {
                //向服務器發送數據
                string msg = command.Text;
                Byte[] outbytes = System.Text.Encoding.Default.GetBytes(msg + "\n");
                stream.Write(outbytes, 0, outbytes.Length);
                byte[] data = new byte[1024];
                //接收服務器回復數據
                if (stream.CanRead)
                {
                    int len = stream.Read(data, 0, data.Length);
                    string msg1 = Encoding.Default.GetString(data, 0, data.Length);
                    string str = "\r\n";
                    char[] str1 = str.ToCharArray();
                    string[] msg2 = msg1.Split(str1);
                    for (int j = 0; j < msg2.Length; j++)
                    {
                        messages.Items.Add(msg2[j]);
                    }
                }
            }
            else
            {
                messages.Items.Add("連接已斷開");
            }

        }

5.信息展示

通過listbox展示所有接收到的消息

6.最終代碼

using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Text;
using System.Threading;

namespace GameWindows
{
    public partial class Form1 : Form
    {
        private NetworkStream stream;
        private TcpClient tcpClient = new TcpClient();
        private String[] pictures={ "\\1.jpg", "\\2.jpg","\\3.jpg","\\4.jpg","5.jpg","6.jpg"};
        private int postion = 0;
        public Form1()
        {
            InitializeComponent();  
            CheckForIllegalCrossThreadCalls = false;
            quitGame.Enabled = false;
            axWindowsMediaPlayer1.Hide();
            pictureBox1.Image = Image.FromFile("G:\\VisualStudioProject\\GameWindows\\resources\\"+pictures[postion]);
        }

        private void start_Click(object sender, EventArgs e)
        {
            //新建線程打開音頻文件
            new Thread(new ThreadStart(beginPlay)).Start();
        }

        private void stop_Click(object sender, EventArgs e)
        {
            //暫定播放
            axWindowsMediaPlayer1.Ctlcontrols.pause();
        }

        private void beginGame_Click(object sender, EventArgs e)
        {

            Thread thread = new Thread(new ThreadStart(connection));
            thread.Start();
            beginGame.Enabled = false;
            quitGame.Enabled = true;

        }

 

        private void quitGame_Click(object sender, EventArgs e)
        {
            tcpClient.Close();
            beginGame.Enabled = true;
            quitGame.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile("G:\\VisualStudioProject\\GameWindows\\resources\\"+pictures[(++postion)%pictures.Length]);
        }



        private void sendButton_Click(object sender, EventArgs e)
        {
            sendCommand();
        }


        public void connection()
        {
            try
            {
                //向指定的IP地址的服務器發出連接請求

                tcpClient.Connect("10.1.230.74", 3900);
                messages.Items.Add("連接成功!");
                stream = tcpClient.GetStream();
                byte[] data = new byte[1024];
                //判斷網絡流是否可讀            
                if (stream.CanRead)
                {
                    int len = stream.Read(data, 0, data.Length);
                    string msg = Encoding.Default.GetString(data, 0, data.Length);
                    string str = "\r\n";
                    char[] str1 = str.ToCharArray();
                    string[] msg1 = msg.Split(str1);
                    for (int j = 0; j < msg1.Length; j++)
                    {
                        messages.Items.Add(msg1[j]);
                    }
                }

            }
            catch (System.Exception ex)
            {
                messages.Items.Add(ex.Message);
            }
        }

        public void beginPlay()
        {
            string s = @"G:\VisualStudioProject\GameWindows\resources\music.mp3";
            axWindowsMediaPlayer1.URL = s;
        }

        public void sendCommand()
        {
            if (tcpClient.Connected)
            {
                //向服務器發送數據
                string msg = command.Text;
                Byte[] outbytes = System.Text.Encoding.Default.GetBytes(msg + "\n");
                stream.Write(outbytes, 0, outbytes.Length);
                byte[] data = new byte[1024];
                //接收服務器回復數據
                if (stream.CanRead)
                {
                    int len = stream.Read(data, 0, data.Length);
                    string msg1 = Encoding.Default.GetString(data, 0, data.Length);
                    string str = "\r\n";
                    char[] str1 = str.ToCharArray();
                    string[] msg2 = msg1.Split(str1);
                    for (int j = 0; j < msg2.Length; j++)
                    {
                        messages.Items.Add(msg2[j]);
                    }
                }
            }
            else
            {
                messages.Items.Add("連接已斷開");
            }

        }
    }
}

三、效果

為瞭方便展示圖片,播放間隔設置的1000ms。

四、總結

C#在網絡編程上特別的方便。

五、參考

https://www.jb51.net/article/230569.htm

六、源碼

https://github.com/TangtangSix/GameWindows

到此這篇關於C#基於TCP實現簡單遊戲客戶端的文章就介紹到這瞭,更多相關C#實現遊戲客戶端內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: