【转】flex与c#基于socket的实时互动网络游戏编程教程一

近些年webGame非常火爆,可惜相关教程实在少之又少,在我学习过程中无数次baidu,google。发现实际涉及wenGame核心的东西基本没有。于是就有了把我学习过程中使用和总结的代码拿上来给大家分享,让有共同爱好的同学们少走弯路。

本教程基于flex与c#,做到完全同步的游戏设计与编写。本教程只提供实现基本功能的代码,只要融会贯通,就能在此基础上制作出无比强大的网络游戏。

这篇教程最好是对c#有一定基础,会使用vs的同学。如果不会,我推荐看一下《c#网络应用编程》。

本教如需转载,请注名作者——汪舰,联系方式sxnrt#126.com。

先来段c#下基由socket连接的代码,什么不是讲flex?flex连接服务器端也是用c#写的(其实也可以用c++或者java写,不过原理都是一样,一通百通)

说明,c#封装了socket,提供操作更方便的Tcpclient与TcpListener,c#属于

服务器端

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

 

namespace TestOnlyServer

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        /// <summary>使用的本机IP地址</summary>

        IPAddress localAddress;

        /// <summary>监听端口</summary>

        private const int port = 51888;

        private TcpListener myListener;

 

        public BinaryReader br;//读取连接用户发来的数据

        private BinaryWriter bw;//给连接用户发送数据

 

        private void Form1_Load(object sender, EventArgs e)

        {

          //  IPAddress[] addrIP = Dns.GetHostAddresses(Dns.GetHostName());

          //  localAddress = addrIP[0];

 

            localAddress = IPAddress.Parse("192.168.1.100");//换成本机ip

        }

 

        private void button1_Click(object sender, EventArgs e)

        {//在设计面版加一个按钮并添加一个事件

            myListener = new TcpListener(localAddress, port); //检听端口设置

            myListener.Start();//开始检听端口

            textBox1.Text = string.Format("开始在{0}:{1}监听客户连接", localAddress, port);

            //创建一个线程监听客户端连接请求

            Thread myThread = new Thread(ListenClientConnect);

            myThread.Start();//开始线程,其实线程的概念很好理解,就是执行一个函数,不过这个函数只和其他函数是并发的,并且占用的服务器资源比较小,因为只用了一部分计算资源

        }

 

        /// <summary>接收客户端连接</summary>

        ///

 

 

 

        private void ListenClientConnect()

        {

 

            TcpClient newClient = null;

            while (true)

            {

                try

                {

                    newClient = myListener.AcceptTcpClient();//当有客户连接时执行一次下面的步骤

                }

                catch

                {

                    //当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常

                    //因此可以利用此异常退出循环

                    break;

                }

                //每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息

                Thread threadReceive = new Thread(ReceiveData);

                threadReceive.Start(newClient);

 

 

                textShow(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint));

//因为textBox1不是由本线程创建的,所以要在线程中操作textBox1必须使用一个动态引用

 

 

            }

 

        }

 

        //现成援引From控件

        delegate void SetTextCallback(string text);

        private void textShow(string str)

        {

            if (textBox1.InvokeRequired)

            {

                SetTextCallback d = textShow;

                textBox1.Invoke(d,str);

            }

 

            else

            {

                this.textBox1.Text = "/n" + textBox1.Text + str;

            }

 

 

        }

 

 

 

        /// <summary>

        /// 处理接收的客户端数据

        /// </summary>

        /// <param name="userState">客户端信息</param>

        private void ReceiveData(object userState)

        {

            TcpClient client = (TcpClient)userState;

            NetworkStream networkStream = client.GetStream();

            //将网络流作为二进制读写对象

            br = new BinaryReader(networkStream);

            bw = new BinaryWriter(networkStream);

            while (true)

            {

                string receiveString = null;

                try

                {

                    //从网络流中读出字符串,此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串

 

                    textShow(string.Format("测试数据1"));

 

                    receiveString = br.ReadString();

                    textShow(string.Format("测试数据2"));

                }

                catch

                {

 

                    break;

                }

 

                textShow(string.Format("[{0}]哈哈哈", receiveString));

 

                //猜测,如果想给所有客用端发信息,在开始时应该把客用端保存在一个array里,然后这里用循环发送

                bw.Write("oyoy");

                bw.Flush();

 

            }

        }

 

    }

}

 

客用端

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net.Sockets;

using System.IO;

using System.Net;

using System.Threading;

 

namespace TestOnlyClient

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

 

        private TcpClient client;

        private BinaryReader br;

        private BinaryWriter bw;

 

        private void Form1_Load(object sender, EventArgs e)

        {

 

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            client = new TcpClient(Dns.GetHostName(), 51888);

            textBox1.Text = "连接咯";

 

 

            Thread threadReceive = new Thread(new ThreadStart(ReceiveData));

            threadReceive.Start();

        }

        private void button2_Click(object sender, EventArgs e)

        {

            try

            {

                NetworkStream networkStream = client.GetStream();

                bw = new BinaryWriter(networkStream);

                bw.Write("gogogo");

                bw.Flush();

            }

            catch

            {

               

            }

        }

 

        private void ReceiveData()

        {

            NetworkStream networkStream = client.GetStream();

            //将网络流作为二进制读写对象

            br = new BinaryReader(networkStream);

            string receiveString = null;

            receiveString = br.ReadString();

            MessageBox.Show(receiveString);

        }

 

    }

}

 

Ok,用vs分别打开2个工程,把ip换成自己本机的ip,你要不知道怎么看本机ip,那我也没啥好说的,呵呵。

这样就创建了纯c#的程序通讯。下一节开始讲如何使用flex与c#做最基本的基于socket的通讯。

posted @ 2011-07-02 13:40  零纪录  阅读(427)  评论(0编辑  收藏  举报