source: 2013/30/MiskaK/MW2(My Warfare 2)/MW2(My Warfare 2)/MW2(My Warfare 2)/OnlineClient.cs @ 4507

Revision 4507, 6.3 KB checked in by anlakane, 6 years ago (diff)

Talletus.

Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Net;
6using System.Net.Sockets;
7using System.IO;
8using System.Threading;
9using My_Warfare_2_Server;
10using Jypeli;
11
12/// <summary>
13/// Verkkopelin verkkotoiminnot.
14/// </summary>
15public class OnlineClient
16{
17    public bool IsStarted { get; private set; }
18
19    Socket SendingSocket { get; set; }
20
21    UdpClient Listener { get; set; }
22
23    Thread ListenThread { get; set; }
24
25    IPAddress ClientIP { get; set; }
26
27    int ClientPort { get; set; }
28
29    IPEndPoint ClientAddress { get; set; }
30
31    IPEndPoint ServerAddress { get; set; }
32
33    String PlayerName { get; set; }
34
35    String Password { get; set; }
36
37    public Player LocalPlayer { get; set; }
38
39    public List<Player> ConnectedPlayers { get; set; }
40
41    /// <summary>
42    /// Käynnistetään online-client.
43    /// </summary>
44    /// <param name="serverAddress">Serverin IP ja portti, jota servu kuuntelee.</param>
45    /// <param name="playerName">Pelaajan nimi.</param>
46    /// <param name="password">Servun salasana.</param>
47    /// <param name="clientPort">Portti, jota client kuuntelee. Välittyy servulle.</param>
48    public void StartClient(IPEndPoint serverAddress, string playerName, string password, int clientPort = 13371)
49    {
50        IsStarted = true; 
51        SendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
52        ClientPort = clientPort;
53        Listener = new UdpClient(ClientPort); // serverAddress.Port
54        //Listener.AllowNatTraversal(true);
55        //Listener.Client = SendingSocket;
56        ServerAddress = serverAddress;
57
58        ClientIP = IPAddress.Parse(GetPublicIP());
59        ClientAddress = new IPEndPoint(ClientIP, ClientPort);
60
61        LocalPlayer = new Player(playerName, -1, ClientAddress);
62        ConnectedPlayers = new List<Player>();
63        PlayerName = playerName;
64        Password = password;
65
66        Connect(ServerAddress);
67
68        ListenThread = new Thread(new ThreadStart(delegate { Listen(new IPEndPoint(IPAddress.Any, ClientPort)); })); // serverin IP, clientin portti
69        ListenThread.Start();
70    }
71
72    /// <summary>
73    /// Sammutetaan online-client.
74    /// </summary>
75    public void StopClient()
76    {
77        SendingSocket.Close();
78        Listener.Close();
79        ListenThread.Abort();
80        IsStarted = false;
81    }
82
83    /// <summary>
84    /// Muodostetaan yhteys serveriin.
85    /// </summary>
86    /// <param name="serverAddress">Serverin IP-osoite.</param>
87    public void Connect(IPEndPoint serverAddress)
88    {
89        Send(new Packet(PacketType.Connect, -1, ClientAddress, new Connect(PlayerName, Password)));
90    }
91
92    /// <summary>
93    /// Clientin kuuntelu ja tiedon vastaanotto.
94    /// </summary>
95    private void Listen(IPEndPoint listenedAddresses)
96    {
97        byte[] receivedData;
98        Packet receivedPacket;
99        try
100        {
101            while (true)
102            {
103                if (!IsStarted) break;
104                receivedData = Listener.Receive(ref listenedAddresses);
105                receivedPacket = Packet.ToPacket(receivedData);
106
107                HandlePacket(receivedPacket);
108            }
109        }
110
111        catch (Exception ex)
112        {
113            //ShowMessage("[ERROR] " + ex.Message); // kaataa servun sammuttaessa
114        }
115    }
116
117    /// <summary>
118    /// Lähetetään tietoa serverille.
119    /// </summary>
120    private void Send(Packet packet)
121    {
122        byte[] packetBuffer = Packet.ToBytes(packet);
123        try
124        {
125            SendingSocket.SendTo(packetBuffer, ServerAddress); // SendingSocket.SendTo
126        }
127
128        catch (SocketException se)
129        {
130            //ShowMessage("[ERROR] " + se.Message);
131        }
132    }
133
134    /// <summary>
135    /// Käsitellään saapunut paketti.
136    /// </summary>
137    /// <param name="packet">Paketti.</param>
138    private void HandlePacket(Packet packet)
139    {
140        switch (packet.Type)
141        {
142            case PacketType.Connect: // ei pitäisi tulla clientille
143                break;
144
145            case PacketType.AcceptConnect:
146                AcceptConnect ac = packet.Data as AcceptConnect;
147                LocalPlayer.PlayerID = ac.ID;
148                ConnectedPlayers = ac.ConnectedPlayers;
149                MW2_My_Warfare_2_.Peli.MessageDisplay.Add("[TESTI] Tuli AcceptConnect!");
150                OnlineGame.StartOnlineGame(ac.GameMode);
151                break;
152
153            case PacketType.Disconnect:
154                StopClient();
155                MW2_My_Warfare_2_.Peli.MessageDisplay.Add((packet.Data as Disconnect).Reason);
156                break;
157
158            case PacketType.PlayerUpdate: // jonkun pelaajan datan muuttuessa päivitetään kyseisen pelaajan tiedot listasta
159                PlayerUpdate pu = packet.Data as PlayerUpdate;
160                for (int i = 0; i < ConnectedPlayers.Count; i++)
161                {
162                    if (ConnectedPlayers[i].PlayerID == pu.UpdatedPlayerID)
163                        ConnectedPlayers[i] = pu.UpdatedPlayerData;
164                }
165                break;
166
167            case PacketType.Shoot:
168                break;
169            case PacketType.ChatMessage:
170                MW2_My_Warfare_2_.Peli.MessageDisplay.Add((packet.Data as ChatMessage).Message); // tähän parempi chatikkuna
171                break;
172            default:
173                break;
174        }
175    }
176
177    /// <summary>
178    /// Selvitetään clientin julkinen IP-osoite.
179    /// </summary>
180    /// <returns>Clientin external IP.</returns>
181    private string GetPublicIP()
182    {
183        String direction = "";
184        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
185        using (WebResponse response = request.GetResponse())
186        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
187        {
188            direction = stream.ReadToEnd();
189        }
190
191        //Search for the ip in the html
192        int first = direction.IndexOf("Address: ") + 9;
193        int last = direction.LastIndexOf("</body>");
194        direction = direction.Substring(first, last - first);
195
196        return direction;
197    }
198
199    /// <summary>
200    /// Vapautetaan resurssit.
201    /// </summary>
202    ~OnlineClient()
203    {
204        StopClient();
205    }
206}
Note: See TracBrowser for help on using the repository browser.