服务端 --接收到消息,原样返回
using System; using System.Net; using System.Net.Sockets; namespace LuaFramework_UGUI_master_Server { 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, 1234); listenfd.Bind(ipEp); listenfd.Listen(0); Console.WriteLine("服务器启动成功"); while (true) { Socket connfd = listenfd.Accept(); Console.WriteLine("服务器Accept"); byte[] readBuffer = new byte[100]; int count = connfd.Receive(readBuffer); 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.ASCII.GetString(readBuffer, 6, strLen); Console.WriteLine("【服务器接收】长度:" + messageLen); Console.WriteLine("【服务器接收】协议号:" + protocal); Console.WriteLine("【服务器接收】字符串:" + str); //返回消息 byte[] writeBuffer = new byte[100]; Array.Copy(readBuffer, writeBuffer,count); connfd.Send(writeBuffer); } } } }
客户端:
Main.lua -- 建立连接
require "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
Network.lua -- 接收、发送消息
Network = {}; --协议 Protocal = { Connect = ‘101‘; --连接服务器 Exception = ‘102‘; --异常掉线 Disconnect = ‘103‘; --正常断线 Message = ‘104‘; --接收消息 } --接收Socket消息-- function Network.OnSocket(key, data) if key == 101 then LuaFramework.Util.Log(‘OnSocket Connect‘); Send() elseif key == 104 then LuaFramework.Util.Log(‘OnSocket Message‘); local str = data:ReadString(); LuaFramework.Util.Log(‘Received String : ‘..str); else LuaFramework.Util.Log(‘OnSocket Other : ‘..key); end end --发送Socket消息-- function Send() --组装数据 local buffer = LuaFramework.ByteBuffer.New(); buffer:WriteShort(Protocal.Message); buffer:WriteString("Unity3d Online Game Book"); --发送 local LuaHelper = LuaFramework.LuaHelper; local networkMgr = LuaHelper.GetNetManager(); networkMgr:SendMessage(buffer); LuaFramework.Util.Log("Data Send Complete"); end
时间: 2024-10-20 14:17:38