public void SetupSSLPort() { _application.Settings.Logging.Enabled = true; _application.Settings.Logging.LogTCPIP = true; _application.Settings.Logging.EnableLiveLogging(true); TCPSocket cs = new TCPSocket(); if (!cs.Connect(250)) { Assert.Fail("Could not connect to SSL server."); } cs.Disconnect(); for (int i = 0; i <= 40; i++) { Assert.IsTrue(i != 40); string liveLog = _application.Settings.Logging.LiveLog; if (liveLog.Contains("SSL handshake with client failed.")) { break; } Thread.Sleep(250); } _application.Settings.Logging.EnableLiveLogging(false); }
public void TestLongSMTPCommand() { TCPSocket socket = new TCPSocket(); socket.Connect(25); // Build a large string... StringBuilder sb = new StringBuilder(); sb.Append("A01"); for (int i = 0; i < 1000000; i++) { sb.Append("01234567890"); } int length = sb.Length; sb.Append(Environment.NewLine); for (int i = 0; i < 100; i++) { try { socket.Send(sb.ToString()); } catch (Exception) { return; } } socket.Send("\r\n"); string result = socket.Receive(); socket.Disconnect(); }
public void TestLongLineInIMAPConversation() { // hMailServer is kind and allows up to 1000000 octets. StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.Append("1234567890"); } sb.Append(".com\r\n"); string command = "A03 NOOP " + sb.ToString(); TCPSocket socket = new TCPSocket(); Assert.IsTrue(socket.Connect(143)); socket.Receive(); socket.Send(command); try { string response = socket.Receive(); Assert.IsTrue(response.StartsWith("* BYE")); } catch (System.Net.Sockets.SocketException ex) { Assert.IsTrue(ex.ErrorCode == 10054); } socket.Disconnect(); }
public Client(TCPSocket sock) { Log.Info("Client", "Creating new connection to EVEmu Server"); connection = new TCPSocket(26000, false); if (connection.Connect("mmoemulators.com") == false) { Log.Error("Client", "Cannot connect to EVEmu Server on port 25999"); CloseConnection(); return; } clientPacketizer = new StreamPacketizer(); serverPacketizer = new StreamPacketizer(); socket = sock; serverReceive = new AsyncCallback(ServerAsyncReceive); clientReceive = new AsyncCallback(ClientAsyncReceive); // Give time to the socket Thread.Sleep(2000); AsyncState serverState = new AsyncState(); connection.Socket.BeginReceive(serverState.buffer, 0, 8192, SocketFlags.None, serverReceive, serverState); AsyncState clientState = new AsyncState(); socket.Socket.BeginReceive(clientState.buffer, 0, 8192, SocketFlags.None, clientReceive, clientState); }
public void TestLongLineInPOP3Conversation() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 400; i++) { sb.Append("1234567890"); } sb.Append(".com"); string command = "NOOP " + sb.ToString(); TCPSocket socket = new TCPSocket(); Assert.IsTrue(socket.Connect(110)); socket.Receive(); socket.Send(command + "\r\n"); string response = socket.Receive(); Assert.IsFalse(response.StartsWith("+OK")); socket.Disconnect(); }
public bool connect()//通过按键connect { if (TCPSocket.Connect()) { isConnect = true; } return(isConnect); }
public void TestLongSMTPDataSessionIncludingNewline() { long memoryUsage = Shared.GetCurrentMemoryUsage(); _application.Settings.MaxMessageSize = 0; TCPSocket socket = new TCPSocket(); socket.Connect(25); socket.Receive(); socket.Send("HELO test.com\r\n"); socket.Receive(); // Build a large string... StringBuilder sb = new StringBuilder(); sb.Append("A01"); for (int i = 0; i < 10000; i++) { sb.Append("01234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890\r\n"); } int length = sb.Length; sb.Append(Environment.NewLine); socket.Send("MAIL FROM: [email protected]\r\n"); socket.Receive(); socket.Send("RCPT TO: [email protected]\r\n"); socket.Receive(); socket.Send("DATA\r\n"); socket.Receive(); for (int i = 0; i < 100; i++) { Shared.AssertLowMemoryUsage(memoryUsage + 30); try { socket.Send(sb.ToString()); } catch (Exception) { return; } } socket.Send("\r\n.\r\n"); string result = socket.Receive(); Assert.IsTrue(result.StartsWith("250")); socket.Send("QUIT\r\n"); result = socket.Receive(); socket.Disconnect(); POP3Simulator.AssertMessageCount(_domain.Accounts[0].Address, "test", 1); }
public void TestLongSMTPDataSessionWithoutNewline() { long memoryUsage = Shared.GetCurrentMemoryUsage(); TCPSocket socket = new TCPSocket(); socket.Connect(25); socket.Receive(); socket.Send("HELO test.com\r\n"); socket.Receive(); // Build a large string... StringBuilder sb = new StringBuilder(); sb.Append("A01"); for (int i = 0; i < 10000; i++) { sb.Append("01234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890"); } int length = sb.Length; socket.Send("MAIL FROM: [email protected]\r\n"); socket.Receive(); socket.Send("RCPT TO: [email protected]\r\n"); socket.Receive(); socket.Send("DATA\r\n"); socket.Receive(); for (int i = 0; i < 1000; i++) { Shared.AssertLowMemoryUsage(memoryUsage + 30); try { socket.Send(sb.ToString()); } catch (Exception) { return; } } socket.Send("\r\n.\r\n"); string result = socket.Receive(); Assert.IsTrue(result.StartsWith("554 Too long line was received. Transmission aborted.")); socket.Send("QUIT\r\n"); result = socket.Receive(); socket.Disconnect(); }
public static async Task GetFile(string path, string filename) { path += filename; IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["Ip"].ToString()), int.Parse(ConfigurationManager.AppSettings["Port"].ToString())); using (var socket = new TCPSocket(StaticData.MyAddress, ipPoint)) { await socket.Connect(); var bytePath = ASCIIEncoding.ASCII.GetBytes(filename.ToArray()); var toSend = new byte[bytePath.Length + 1]; toSend[0] = 77; for (int i = 0; i < bytePath.Length; i++) { toSend[i + 1] = bytePath[i]; } await socket.SendData(toSend); var temp = new byte[12]; await socket.ReceiveData(temp); var length = BitConverter.ToInt64(temp, 0); if (length == 0) { MessageBox.Show("File doesn't exist"); return; } int packageSize = BitConverter.ToInt32(temp, 8); var data = new byte[packageSize]; using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write)) { int iter = (int)((length) / packageSize); for (int i = 0; i < iter; i++) { data = new byte[packageSize]; await socket.ReceiveData(data); await file.WriteAsync(data, 0, packageSize); await socket.SendData(new byte[] { 255 }); } var bytes = await socket.ReceiveData(data); await file.WriteAsync(data, 0, bytes); } } }
public CarRep() { try { IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["Ip"].ToString()), int.Parse(ConfigurationManager.AppSettings["Port"].ToString())); socket = new TCPSocket(StaticData.MyAddress, ipPoint); socket.Connect().Wait(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void Connect() { TCPSocket socket = new TCPSocket(); socket.Connect(address.text, int.Parse(port.text)); // Faire la gestion d'erreurs si connect renvoie false Byte[] message = socket.Recv(); System.Text.Encoding enc = System.Text.Encoding.ASCII; Debug.Log(enc.GetString(message)); socket.Send(enc.GetBytes("bite")); }
public void TestSendToTooManyRecipients() { hMailServer.Accounts accounts = _domain.Accounts; hMailServer.Account senderAccount = SingletonProvider <Utilities> .Instance.AddAccount(accounts, string.Format("*****@*****.**"), "test"); List <string> recipients = new List <string>(); TCPSocket sock = new TCPSocket(); sock.Connect(25); string result = sock.ReadUntil("\r\n"); sock.Send("EHLO test.com\r\n"); result = sock.ReadUntil("\r\n"); Assert.IsTrue(result.StartsWith("250")); sock.Send("MAIL FROM: [email protected]\r\n"); result = sock.ReadUntil("\r\n"); Assert.IsTrue(result.StartsWith("250")); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 51000; i++) { string address = string.Format("test{0}@gmail.com", i); sock.Send(string.Format("RCPT TO: <{0}>\r\n", address)); result = sock.ReadUntil("\r\n"); if (i < 50000) { Assert.IsTrue(result.StartsWith("250")); } else { long perfor = watch.ElapsedMilliseconds; Assert.IsFalse(result.StartsWith("250")); } } }
public void TestSMTPServerAuthPlain() { _settings.AllowSMTPAuthPlain = true; TCPSocket sock = new TCPSocket(); sock.Connect(25); Assert.IsTrue(sock.Receive().StartsWith("220")); sock.Send("EHLO test.com\r\n"); Assert.IsTrue(sock.Receive().StartsWith("250")); sock.Send("AUTH PLAIN\r\n"); Assert.IsTrue(sock.Receive().StartsWith("334")); string str = "\t" + GetUsername() + "\t" + GetPassword(); sock.Send(EncodeBase64(str) + "\r\n"); Assert.IsTrue(sock.Receive().StartsWith("535")); EnsureNoPassword(); }
public void TestPOP3DownloadOfLargeMessage() { TestLongSMTPDataSessionIncludingNewline(); POP3Simulator.AssertMessageCount("*****@*****.**", "test", 1); TCPSocket socket = new TCPSocket(); socket.Connect(110); // Receive welcome message. string sData = socket.Receive(); socket.Send("USER " + "*****@*****.**" + "\r\n"); sData = socket.ReadUntil("+OK"); socket.Send("PASS " + "test" + "\r\n"); sData = socket.ReadUntil("+OK"); socket.Send("RETR 1\r\n"); string sRetVal = ""; while (sRetVal.IndexOf("\r\n.\r\n") < 0) { if (sRetVal.IndexOf("-ERR no such message") >= 0) { socket.Disconnect(); Assert.Fail("Nope"); } sRetVal = socket.Receive(); } socket.Send("DELE 1\r\n"); sData = socket.ReadUntil("+OK"); socket.Send("QUIT\r\n"); sData = socket.ReadUntil("+OK"); socket.Disconnect(); }
public void TestSMTPServerAuthLoginUsernameAsThirdParameter() { _settings.AllowSMTPAuthPlain = true; TCPSocket sock = new TCPSocket(); sock.Connect(25); Assert.IsTrue(sock.Receive().StartsWith("220")); sock.Send("EHLO test.com\r\n"); Assert.IsTrue(sock.Receive().StartsWith("250")); string base64EncodedUsername = EncodeBase64(GetUsername()); sock.Send("AUTH LOGIN " + base64EncodedUsername + "\r\n"); Assert.IsTrue(sock.Receive().StartsWith("334")); sock.Send(EncodeBase64(GetPassword()) + "\r\n"); Assert.IsTrue(sock.Receive().StartsWith("535")); EnsureNoPassword(); }
public GenericRep() { try { //IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8005); //IPEndPoint ipPoint1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8004); //socket = new TCPSocket(ipPoint1, ipPoint); IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["Ip"].ToString()), int.Parse(ConfigurationManager.AppSettings["Port"].ToString())); socket = new TCPSocket(StaticData.MyAddress, ipPoint); socket.Connect(); } catch (Exception ex) { MessageBox.Show(ex.Message); } switch (typeof(T).Name) { case "Car": first = 2; break; case "User": first = 1; break; case "Parking": first = 5; break; case "Slot": first = 4; break; case "Talon": first = 3; break; } }
// Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.A)) { tcpSocket.Connect("127.0.0.1", 18002); } if (Input.GetKeyDown(KeyCode.B)) { byte[] tmpBytes = System.Text.Encoding.Default.GetBytes(" 1707 !!!"); tcpSocket.Send(tmpBytes); } if (tcpSocket != null && tcpSocket.Connected()) { tcpSocket.Recive(); } }
public void AuthShouldUpdateLastLogonTime() { hMailServer.Account account = SingletonProvider<Utilities>.Instance.AddAccount(_domain, "*****@*****.**", "test"); DateTime lastLogonTimeBefore = Convert.ToDateTime(account.LastLogonTime); System.Threading.Thread.Sleep(1000); TCPSocket sock = new TCPSocket(); sock.Connect(25); Assert.IsTrue(sock.Receive().StartsWith("220")); sock.Send("EHLO test.com\r\n"); Assert.IsTrue(sock.Receive().StartsWith("250")); string base64EncodedUsername = EncodeBase64("*****@*****.**"); sock.Send("AUTH LOGIN " + base64EncodedUsername + "\r\n"); Assert.IsTrue(sock.Receive().StartsWith("334")); sock.Send(EncodeBase64("test") + "\r\n"); Assert.IsTrue(sock.Receive().StartsWith("235")); DateTime lastLogonTimeAfter = Convert.ToDateTime(SingletonProvider<Utilities>.Instance.GetApp().Domains[0].Accounts[0].LastLogonTime); Assert.AreNotEqual(lastLogonTimeBefore, lastLogonTimeAfter); }
public void ConnectNetwork(bool needLoad = true, System.Action <bool> callback = null) { //获取服务器配置 JsonData server = GameData.GetServerConfig(); string ip = (string)server["ip"]; string port = (string)server["port"]; Debug.Log("Client.ConnectNetwork Start Connect Server ip = " + ip + " port = " + port); //连接 if (true == needLoad) { LoadLayerManager.Instance.AddLoad(); } TCPSocket.Connect(ip, port, (isOK) => { if (true == needLoad) { LoadLayerManager.Instance.RemoveLoad(); } callback(isOK); }); }
public void TestManyTCPIPConnections() { Utilities.DeleteCurrentDefaultLog(); const int count = 1000; List <TCPSocket> sockets = new List <TCPSocket>(); for (int i = 0; i < count; i++) { TCPSocket socket = new TCPSocket(); Assert.IsTrue(socket.Connect(25)); sockets.Add(socket); } foreach (TCPSocket socket in sockets) { socket.Disconnect(); } string log = Utilities.ReadCurrentDefaultLog(); }
static void Main(string[] args) { Log.Init("evesharp"); Log.Info("Main", "Starting node..."); Log.Info("Database", "Loading database.conf file"); string[] lines = File.ReadAllLines("database.conf"); Database.Database.Username = lines[0]; Database.Database.Password = lines[1]; Database.Database.Host = lines[2]; Database.Database.DB = lines[3]; Log.Trace("Database", "Connecting to database..."); if (Database.Database.Init() == false) { Log.Error("Main", "Cannot connect to database"); while (true) { ; } } /* * SHA1 sha1 = SHA1.Create(); * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password")); * char[] strHash = new char[20]; * * for (int i = 0; i < 20; i++) * { * strHash[i] = (char)hash[i]; * } * * string str = new string(strHash); * * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);"); * * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', SHA1('password'), 2, 0, 0);");*/ Log.Info("Main", "Connection to the DB sucessfull"); Log.Info("Main", "Generating default cache data"); Cache.GenerateCache(); Log.Debug("Main", "Done"); Log.Info("Main", "Connecting to proxy..."); proxyConnection = new TCPSocket(ushort.Parse(proxy[0, 1]), false); if (proxyConnection.Connect(proxy[0, 0]) == false) { Log.Error("Main", "Cannot connect to proxy. Halting"); Database.Database.Stop(); while (true) { ; } } Log.Trace("Main", "Server started"); while (true) { Thread.Sleep(1); try { byte[] data = new byte[proxyConnection.Available]; int bytes = proxyConnection.Recv(data); if (bytes == -1) { // Proxy is closing, shutdown the node break; } else if (bytes > 0) { packetizer.QueuePackets(data, bytes); int p = packetizer.ProcessPackets(); for (int i = 0; i < p; i++) { byte[] packet = packetizer.PopItem(); PyObject obj = Unmarshal.Process <PyObject>(packet); if (obj is PyObjectData) { PyObjectData info = obj as PyObjectData; if (info.Name == "machoNet.nodeInfo") { // Update our local info NodeInfo nodeinfo = new NodeInfo(); if (nodeinfo.Decode(info) == true) { nodeID = nodeinfo.nodeID; Log.Debug("Main", "Found machoNet.nodeInfo, our new node id is " + nodeID.ToString("X4")); SystemManager.LoadSolarSystems(nodeinfo.solarSystems); } } else { // Client packet PyPacket clientpacket = new PyPacket(); if (clientpacket.Decode(info) == false) { Log.Error("Main", "Unknown packet"); } else { // Something similar to Async calls new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket); } } } else if (obj is PyChecksumedStream) // Checksumed packets { PyPacket clientpacket = new PyPacket(); if (clientpacket.Decode(obj) == false) { Log.Error("Main", "Cannot decode packet"); } else { new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket); } } else if (obj is PyTuple) { // The only tuple packet is the LowLevelVersionExchange LowLevelVersionExchange ex = new LowLevelVersionExchange(); if (ex.Decode(obj) == false) { Log.Error("Main", "LowLevelVersionExchange error"); } // Reply with the node LowLevelVersionExchange LowLevelVersionExchange reply = new LowLevelVersionExchange(); reply.codename = Common.Constants.Game.codename; reply.birthday = Common.Constants.Game.birthday; reply.build = Common.Constants.Game.build; reply.machoVersion = Common.Constants.Game.machoVersion; reply.version = Common.Constants.Game.version; reply.region = Common.Constants.Game.region; Send(reply.Encode(true)); } else if (obj is PyObjectEx) { Log.Error("PyObjectEx", PrettyPrinter.Print(obj)); } else { Log.Error("Main", PrettyPrinter.Print(obj)); Log.Error("Main", "Unhandled packet type"); } } } } catch (Exception) { } } /* Code to ADD an account: * SHA1 sha1 = SHA1.Create(); * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password")); * char[] strHash = new char[20]; * * for (int i = 0; i < 20; i++) * { * strHash[i] = (char)hash[i]; * } * * string str = new string(strHash); * * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);"); */ }
public void TestEHLOKeywords() { hMailServer.Application application = SingletonProvider<Utilities>.Instance.GetApp(); hMailServer.Settings settings = _settings; settings.HostName = "examplify.com"; TCPSocket socket = new TCPSocket(); Assert.IsTrue(socket.Connect(25)); string result = socket.Receive(); socket.Send("EHLO example.com\r\n"); result = socket.Receive(); socket.Disconnect(); Assert.IsTrue(result.Contains("250-" + settings.HostName)); }
// Start is called before the first frame update void Start() { TCPSocket socket = new TCPSocket(); socket.Connect("tec.wf", 23); }
private static byte[] SendMessageToSocketAndListenToCallback(IPEndPoint source, IPEndPoint destination, byte[] bufferToSend, BytesReceivedDelegate callBack, ProtocolType protocol, byte[] heartbeatMessage, Regex responseFormat, BytesReceivedDelegate heartbeatCallback, bool isSynchronious, bool useSocketPool) { Socket TCPSocket = null; if (useSocketPool) { TCPSocket = CheckIfSocketAlreadyOpen(source, destination); } HeartbeatInfo info = null; try { if (TCPSocket == null) { if (protocol == ProtocolType.Udp) { TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, protocol); } else if (protocol == ProtocolType.Tcp) { TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocol); } TCPSocket.Bind(source); if (protocol == ProtocolType.Tcp) { TCPSocket.Connect(destination); if (useSocketPool) { info = new HeartbeatInfo(TCPSocket, heartbeatMessage, responseFormat, heartbeatCallback, 10); info.CallbackDelegate += new BytesReceivedDelegate(CheckIfHeartbeatFailed); lock (openSocketsList) { openSocketsList.Add(info); } } } } // lock (TCPSocket) { if (bufferToSend != null) { if (protocol == ProtocolType.Tcp) { TCPSocket.Send(bufferToSend); } else if (protocol == ProtocolType.Udp) { TCPSocket.SendTo(bufferToSend, destination); } } StateObject state = new StateObject(); if (isSynchronious) { TCPSocket.ReceiveTimeout = 5000; TCPSocket.Receive(state.buffer); if (!useSocketPool) { TCPSocket.Shutdown(SocketShutdown.Both); TCPSocket.Close(); } return(state.buffer); } else if (callBack != null) { state.workSocket = TCPSocket; state.callbackDelegate += callBack; if (info != null) { state.callbackDelegate += info.ProcessMessageReceivedFromSocket; } TCPSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } // } return(null); } catch (Exception ex) { LoggingHelper.LogExceptionInApplicationLog(ex.Source, ex, EventLogEntryType.Error); LoggingHelper.WriteExceptionLogEntry(ex.Source, ex); if (TCPSocket != null && TCPSocket.Connected) { TCPSocket.Shutdown(SocketShutdown.Both); TCPSocket.Close(); } } return(null); }
static void Main(string[] args) { Log.Init("evesharp"); Log.Info("Main", "Starting node..."); Log.Trace("Database", "Connecting to database..."); if (Database.Database.Init() == false) { Log.Error("Main", "Cannot connect to database"); while (true) { ; } } /* * DBRowDescriptor descriptor = new DBRowDescriptor(); * * descriptor.AddColumn("itemID", FieldType.I4); * descriptor.AddColumn("custominfo", FieldType.Str); * * PyPackedRow packed = new PyPackedRow(descriptor); * * packed.SetValue("itemID", new PyInt(500)); * packed.SetValue("custominfo", new PyString("hello world")); * * byte[] marshaled = Marshal.Marshal.Process(packed); * * PyPackedRow unmarshaled = Unmarshal.Process<PyPackedRow>(marshaled); * * Console.WriteLine(PrettyPrinter.Print(unmarshaled)); */ byte[] raw = new byte[] { 1, 0, 55, 1, 22, 33, 0, 33, 25, 33, 14, 0, 0, 25, 45 }; MemoryStream output = new MemoryStream(raw); BinaryReader reader = new BinaryReader(output); MemoryStream stream = new MemoryStream(); BinaryWriter streamWriter = new BinaryWriter(stream); BinaryReader streamReader = new BinaryReader(stream); PyPackedRow.ZeroCompress(reader, output, streamWriter); byte[] compressed = stream.ToArray(); stream.Seek(0, SeekOrigin.Begin); byte[] uncompress = PyPackedRow.LoadZeroCompressed(streamReader); while (true) { Thread.Sleep(1); } /* * SHA1 sha1 = SHA1.Create(); * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password")); * char[] strHash = new char[20]; * * for (int i = 0; i < 20; i++) * { * strHash[i] = (char)hash[i]; * } * * string str = new string(strHash); * * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);"); */ Log.Info("Main", "Connection to the DB sucessfull"); Log.Trace("Main", "Registering services..."); SvcMgr.AddService(new Services.Network.machoNet()); SvcMgr.AddService(new Services.Network.alert()); SvcMgr.AddService(new Services.CacheSvc.objectCaching()); Log.Info("Main", "Done"); Log.Info("Main", "Connecting to proxy..."); proxyConnection = new TCPSocket(ushort.Parse(proxy[0, 1]), false); if (proxyConnection.Connect(proxy[0, 0]) == false) { Log.Error("Main", "Cannot connect to proxy. Halting"); Database.Database.Stop(); while (true) { ; } } Log.Trace("Main", "Server started"); while (true) { Thread.Sleep(1); try { byte[] data = new byte[proxyConnection.Available]; int bytes = proxyConnection.Recv(data); if (bytes == -1) { // Proxy is closing, shutdown the node break; } else if (bytes > 0) { packetizer.QueuePackets(data, bytes); int p = packetizer.ProcessPackets(); for (int i = 0; i < p; i++) { byte[] packet = packetizer.PopItem(); PyObject obj = Unmarshal.Process <PyObject>(packet); if (obj is PyObjectData) { PyObjectData info = obj as PyObjectData; if (info.Name == "machoNet.nodeInfo") { // Update our local info NodeInfo nodeinfo = new NodeInfo(); if (nodeinfo.Decode(info) == true) { nodeID = nodeinfo.nodeID; SystemManager.LoadSolarSystems(nodeinfo.solarSystems); } } else { // Client packet PyPacket clientpacket = new PyPacket(); if (clientpacket.Decode(info) == false) { Log.Error("Main", "Unknown packet"); } else { // Something similar to Async calls new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket); } } } else if (obj is PyChecksumedStream) // Checksumed packets { PyPacket clientpacket = new PyPacket(); if (clientpacket.Decode(obj) == false) { Log.Error("Main", "Cannot decode packet"); } else { new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket); } } else if (obj is PyTuple) { // The only tuple packet is the LowLevelVersionExchange LowLevelVersionExchange ex = new LowLevelVersionExchange(); if (ex.Decode(obj) == false) { Log.Error("Main", "LowLevelVersionExchange error"); } // Reply with the node LowLevelVersionExchange LowLevelVersionExchange reply = new LowLevelVersionExchange(); reply.codename = Common.Constants.Game.codename; reply.birthday = Common.Constants.Game.birthday; reply.build = Common.Constants.Game.build; reply.machoVersion = Common.Constants.Game.machoVersion; reply.version = Common.Constants.Game.version; reply.region = Common.Constants.Game.region; Send(reply.Encode(true)); } else if (obj is PyObjectEx) { Log.Error("PyObjectEx", PrettyPrinter.Print(obj)); } else { Log.Error("Main", PrettyPrinter.Print(obj)); Log.Error("Main", "Unhandled packet type"); } } } } catch (Exception) { } } /* Code to ADD an account: * SHA1 sha1 = SHA1.Create(); * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password")); * char[] strHash = new char[20]; * * for (int i = 0; i < 20; i++) * { * strHash[i] = (char)hash[i]; * } * * string str = new string(strHash); * * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);"); */ }