LuaFramework框架自带的Network网络连接(socket)

Main.lua – 建立连接
一般情况下,LuaGame脚本中也有一段启动Socket连接的代码,不想删掉可以直接修改端口号和ip地址,
要么删了写在main脚本中,要么改Game中的socket 一定!!! 一定!!!

--注册网络连接脚本--
require "Logic/Network"

--主入口函数。从这里开始lua逻辑
function Main()
    --网络连接
    print("网络连接");
    local networkMgr = LuaHelper.GetNetManager();
    local AppConst = LuaFramework.AppConst;
    AppConst.SocketPort = 1234;
    AppConst.SocketAddress = "127.0.0.1";
    networkMgr:SendConnect();
end

收发消息的协议(LuaFramework自带这个协议脚本,可以自己更改定义协议,相对应的拆包方式也要更改一下)
拆包协议的位置:
框架自带的SocketClient脚本(C#脚本)

--协议 
Protocal = {
       Connect = '101';         --连接服务器
       Exception = '102';       --异常掉线
       Disconnect = '103';      --正常断线  
       Message = '104';         --接收消息
}

Network.lua – 接收、发送消息

Network = {};

--接收Socket消息--
function Network.OnSocket(key, data)
    if key == 101 then
        LuaFramework.Util.Log('服务器已连接');
        Send()
    elseif key == 104 then
        LuaFramework.Util.Log('收到服务器消息');
        local str = data:ReadString();
        LuaFramework.Util.Log('服务器发来的消息是 : '..str);
    else
        LuaFramework.Util.Log('错误代码 : '..key);
    end
end
--发送Socket消息--
function Send()
    --组装数据
    local buffer = LuaFramework.ByteBuffer.New();
    buffer:WriteShort(Protocal.Message);
    buffer:WriteString("测试链接服务器");
    --发送
    local LuaHelper = LuaFramework.LuaHelper;
    local networkMgr = LuaHelper.GetNetManager();
    networkMgr:SendMessage(buffer);
    LuaFramework.Util.Log("消息发送成功");
end

服务器代码(收到消息立马回执相同消息,测试使用)

using System;
using System.Net;
using System.Net.Sockets;

namespace LuaFrameworkServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEp = new IPEndPoint(ipAdr, 10004);
            Console.WriteLine("正在绑定端口号");
            listenfd.Bind(ipEp);
            Console.WriteLine("端口号绑定完成,开启监听");
            listenfd.Listen(0);
            Console.WriteLine("监听开启完毕");
            Console.WriteLine("服务器启动成功");
           
            while (true)
            {
                try
                {
                    Socket connfd = listenfd.Accept();
                    Console.WriteLine("服务器Accept");
                    byte[] readBuffer = new byte[512];
                    int count = connfd.Receive(readBuffer);
                    Console.WriteLine("服务器接收完毕!!");
                    string showStr = "";
                    for (int i = 0; i < count; i++)
                    {
                        int b = (int)readBuffer[i];
                        showStr += b.ToString() + " ";
                    }
                    Console.WriteLine("服务器接收字节流:" + showStr);
                    //解析消息
                    //1.前两个字节为消息长度
                    //2.后两个字节为协议
                    //3.后面的字节为消息内容
                    Int16 messageLen = BitConverter.ToInt16(readBuffer, 0);
                    Int16 protocal = BitConverter.ToInt16(readBuffer, 2);
                    Int16 strLen = BitConverter.ToInt16(readBuffer, 4);
                    string str = System.Text.Encoding.UTF8.GetString(readBuffer, 6, strLen);
                    Console.WriteLine("【服务器接收】长度:" + messageLen);
                    Console.WriteLine("【服务器接收】协议号:" + protocal);
                    Console.WriteLine("【服务器接收的消息内容】字符串:" + str);
                    //返回消息
                    byte[] writeBuffer = new byte[count];
                    Array.Copy(readBuffer, writeBuffer, count);

                    connfd.Send(writeBuffer);
                    Console.WriteLine("消息发送完毕");
                }
                catch (Exception e)
                {

                   //打印错误原因 
                   Console.WriteLine(e.ToString());
                }
               
            }
        }
    }
}

如果想实现服务器向Lua客户端发送自定义消息,就需要模仿LuaFramework框架的粘包协议,当然也可以自己吧客户端以及服务器的协议重新定义 代码如下:

/// 
        /// 写数据 模仿LuaFramework框架的粘包协议
        /// 
        public static byte[] WtiteMessage(int protocal,string msg)
        {
            MemoryStream stream= new MemoryStream();
            BinaryWriter bw = new BinaryWriter(stream);
            bw.Write((ushort)protocal);
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            bw.Write((ushort)bytes.Length);
            bw.Write(bytes);
            bw.Flush();
            byte[] message = stream.ToArray();
           
            MemoryStream ms = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(ms);
            ushort msglen = (ushort)message.Length;
            writer.Write(msglen);
            writer.Write(message);
            writer.Flush();
            
            byte[] payload = ms.ToArray();
            //返回粘好的数据包,可以直接调用Socket.send()方法发送
            return payload;
            
        }

你可能感兴趣的:(Lua)