using CTZLauncher.Modules.Minecraft; using LitJson; using System; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Threading; namespace CTZLauncher.Tools { public class MinecraftServer { string address; int port; bool finish; ServerInfo serverinfo; /// /// 获取服务器详细信息 /// /// 服务器地址 /// 服务器端口 public MinecraftServer(string address, int port) { this.address = address; this.port = port; } /// /// 模仿C#的Application.Doevent函数。可以适当添加try catch 模块 /// public void DoEvent() { DispatcherFrame frame = new DispatcherFrame(); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame); Dispatcher.PushFrame(frame); } public object ExitFrame(object f) { ((DispatcherFrame)f).Continue = false; return null; } /// /// 异步获取服务器信息 /// /// 服务器信息 public ServerInfo DoAsync() { new Thread(new ThreadStart(GetInfoAsync)).Start(); while (finish == false) { DoEvent(); } return serverinfo; } /// /// 获取服务器信息 /// /// 服务器信息 public ServerInfo Do() { return GetInfo(); } public void GetInfoAsync() { finish = false; serverinfo = GetInfo(); finish = true; } public ServerInfo GetInfo() { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { try { client.Connect(address, port); if (client.Connected) { client.Send(new byte[] { 0x0f, 0x00, 0x04, 0x09, 0x31, 0x32, 0x37, 0x2e, 0x30, 0x2e, 0x30, 0x2e, 0x31, 0x63, 0xdd, 0x01 }); client.Send(new byte[] { 0x01, 0x00 }); byte[] header = new byte[5]; client.Receive(header, header.Length, SocketFlags.None); byte[] buffer = new byte[1024]; int recover = client.Receive(buffer, buffer.Length, SocketFlags.None); byte[] data = new byte[recover]; Array.Copy(buffer, data, recover); string info = Encoding.UTF8.GetString(data); return JsonMapper.ToObject(info); } Console.WriteLine("网络连接失败!"); return null; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return null; } } } } }