public void ConnectToServer() { IPAddress ip = IPAddress.Parse("172.20.10.4"); IPEndPoint ipe = new IPEndPoint(ip, 1111); TcpClient tcpClient = new TcpClient(); try { tcpClient.Connect(ipe); if (tcpClient.Connected) { MessageBox.Show("連線成功"); CommunicationBase cb = new CommunicationBase(); cb.SendData("測試訊息", tcpClient); MessageBox.Show(cb.ReceiveData(tcpClient)); } else { Console.WriteLine("連線失敗"); } } catch (Exception e) { tcpClient.Close(); Console.WriteLine(e.Message); } }
private void ListenClient() { TcpClient client = tcpClient; Thread thread = ClThread; while (true) { try { CommunicationBase cb = new CommunicationBase(); string data = cb.ReceiveData(client); string cmd = data.Substring(0, 1); int attHp = 0; Monster monster = (Monster)HT[client]; switch (cmd) { case "1": attHp = int.Parse(data.Substring(1)); monster.BeAttacked(attHp); break; case "9": HT.Remove(client); thread.Abort(); break; } //MessageBox.Show(monster.HP.ToString()); string msg = monster.HP.ToString() + "," + new Random().Next(50).ToString(); cb.SendData(msg, client); } catch (Exception e) { Console.WriteLine(e.Message); throw; } } }