C#基于TCP实现简单游戏客户端

Posted 醉意丶千层梦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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连接,并且禁用登录按钮使能退出按钮

 private void beginGame_Click(object sender, EventArgs e)
        

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

        

退出游戏则端口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://blog.csdn.net/qq_43279579/article/details/109693257

六、源码

https://github.com/TangtangSix/GameWindows

以上是关于C#基于TCP实现简单游戏客户端的主要内容,如果未能解决你的问题,请参考以下文章

C#里实现简单的异步TCP服务器

C#里实现简单的异步TCP服务器

游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)

游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)

C#基于UDP实现简单客户端和服务器消息发送和接收

C# 基于TCP 实现扫描指定ip端口