Advertisement
Guest User

AxiomGameServer

a guest
Aug 15th, 2011
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.99 KB | None | 0 0
  1. //Client Connection Code
  2.  
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Net.Sockets;
  9. using System.Net;
  10. using System.Threading;
  11. using System.IO;
  12. using UnityEngine;
  13. using System.Collections;
  14.  
  15. namespace Axiom_ClientConnection_0_01
  16. {
  17.     public class Connector
  18.     {
  19.         const int READ_BUFFER_SIZE = 255;
  20.         const int TCP_PORT_NUMBER = 65000;
  21.         const int UDP_PORT_NUMBER = 65002;
  22.         private TcpClient connectionClient;
  23.         public Hashtable MultiLocations = new Hashtable();
  24.  
  25.         public struct PlayerLocations
  26.         {
  27.             public Vector3 Position;
  28.             public Quaternion Rotation;
  29.         };
  30.  
  31.         //UdpClient transmissionClient;
  32.         private byte[] readbuffer = new byte[READ_BUFFER_SIZE];
  33.         public string message = "";
  34.         public string result = "";
  35.         private string username;
  36.         IPAddress ipAddress;
  37.         IPEndPoint servIP, listenUDP;
  38.         Thread UDPListenerThread;
  39.         int portNum = new int();
  40.         Socket server = new Socket(AddressFamily.InterNetwork,
  41.                      SocketType.Dgram, ProtocolType.Udp);
  42.         public bool CONNECTED = false;
  43.         public int x = 0;
  44.  
  45.         public Connector() { }
  46.  
  47.         public string ConnectionAttempt(string ServeIP, string PlayUsername)
  48.         {
  49.             username = PlayUsername;
  50.  
  51.             try
  52.             {
  53.                
  54.                 connectionClient = new TcpClient(ServeIP,TCP_PORT_NUMBER);
  55.                 connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
  56.                
  57.                 Login(username);
  58.                 ipAddress = IPAddress.Parse(((IPEndPoint)connectionClient.Client.RemoteEndPoint).Address.ToString());
  59.                 servIP = new IPEndPoint(ipAddress,65002);
  60.                 listenUDP = new IPEndPoint(ipAddress, 0);
  61.                
  62.                 UDPListenerThread = new Thread(receiveUDP);
  63.                 UDPListenerThread.IsBackground = true;
  64.                 UDPListenerThread.Start();
  65.                 return "Connection Succeeded";
  66.             }
  67.             catch(Exception ex) {
  68.                 return (ex.Message.ToString() + "Connection Failed");
  69.             }
  70.         }
  71.  
  72.         private void receiveUDP()
  73.         {
  74.             System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT_NUMBER);
  75.             System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
  76.             server.Bind(serverIP);
  77.          
  78.  
  79.             EndPoint RemoteServ = (EndPoint)listenUDP;
  80.             do
  81.             {
  82.                 byte[] content = new byte[1024];
  83.                 int data = server.ReceiveFrom(content, ref RemoteServ);
  84.  
  85.                 string message = Encoding.ASCII.GetString(content);
  86.                
  87.  
  88.                 ProcessCommands(message);
  89.  
  90.  
  91.             } while (true);
  92.         }
  93.  
  94.         public void Login(string username)
  95.         {
  96.             StreamWriter writer = new StreamWriter(connectionClient.GetStream());
  97.             writer.Write("CONNECT|" + username);
  98.             writer.Flush();
  99.             //connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
  100.         }
  101.  
  102.         public void SendChat(string data)
  103.         {
  104.             SendData(username + "|CHAT|" + data);
  105.         }
  106.  
  107.         public void SendUpdateLocation(string data)
  108.         {
  109.             SendData(username + "|UPDATEPOS|" + data);
  110.         }
  111.  
  112.         public void Disconnect()
  113.         {
  114.             SendData(username + "|DISCONNECT|");
  115.            
  116.             //StreamWriter writer = new StreamWriter(connectionClient.GetStream());
  117.             //writer.Write("DISCONNECT");
  118.             //writer.Flush();
  119.             server.Close();
  120.             UDPListenerThread.Abort();
  121.            
  122.             connectionClient.Close();
  123.            
  124.         }
  125.  
  126.  
  127.         private void DoRead(IAsyncResult ar)
  128.         {
  129.             int BytesRead;
  130.             try
  131.             {
  132.                 BytesRead = connectionClient.GetStream().EndRead(ar);
  133.                 if (BytesRead < 1)
  134.                 {
  135.                     result = "DISCONNECTED";
  136.                     return;
  137.                 }
  138.  
  139.                 string message = Encoding.ASCII.GetString(readbuffer, 0, BytesRead);
  140.                 ProcessCommands(message);
  141.  
  142.                 connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
  143.             }
  144.             catch { }
  145.         }
  146.  
  147.  
  148.         private void SendData(string data)
  149.         {
  150.             //result = data;
  151.             byte[] dataArr = Encoding.ASCII.GetBytes(data);
  152.             try
  153.             {
  154.                 EndPoint servEnd = (EndPoint)servIP;
  155.                 //UDPListenerThread.Suspend();
  156.                 server.SendTo(dataArr, dataArr.Length,SocketFlags.None, servEnd);
  157.                 //UDPListenerThread.Resume();
  158.             }
  159.             catch (Exception e)
  160.             {
  161.             }
  162.         }
  163.  
  164.         private void ProcessCommands(string data)
  165.         {
  166.             string[] dataArr;
  167.  
  168.             dataArr = data.Split((char)124);
  169.  
  170.             switch (dataArr[0])
  171.             {
  172.                 case "JOIN":
  173.                     result = "You have joined the chat!";
  174.                     CONNECTED = true;
  175.                     break;
  176.                 case "CHAT":
  177.                     result = dataArr[1].ToString();
  178.                     break;
  179.                 case "REFUSE":
  180.                     Login(username);
  181.                     result = "Connection refused.  Attempting another login.";
  182.                     break;
  183.                 case "BROAD":
  184.                     result = "SERVER MESSAGE: " + dataArr[1].ToString();
  185.                     break;
  186.                 case "UPDATEPOS":
  187.                     UpdateLoc(dataArr);
  188.                     //x++;
  189.                     break;
  190.                 default:
  191.                     result = "Server sent bad message waiting for retry";
  192.                     break;
  193.             }
  194.         }
  195.  
  196.         private void UpdateLoc(string [] data)
  197.         {
  198.             //result = x.ToString();
  199.             string [] playerLoc;
  200.             for (int i = 1; i < data.Length; i++)
  201.             {
  202.                 playerLoc = data[i].Split(',');
  203.  
  204.                 PlayerLocations PlayerCoord = new PlayerLocations();
  205.                 Vector3 trans1;
  206.                 Quaternion trans2 = new Quaternion();
  207.                 trans1.x = float.Parse(playerLoc[1]);
  208.                 trans1.y = float.Parse(playerLoc[2]);
  209.                 trans1.z = float.Parse(playerLoc[3]);
  210.                 trans2.x = float.Parse(playerLoc[4]);
  211.                 trans2.y = float.Parse(playerLoc[5]);
  212.                 trans2.z = float.Parse(playerLoc[6]);
  213.  
  214.                 PlayerCoord.Position = trans1;
  215.                 PlayerCoord.Rotation = trans2;
  216.  
  217.  
  218.                 if(MultiLocations.ContainsKey(playerLoc[0]))
  219.                 {
  220.                     MultiLocations[playerLoc[0]] = PlayerCoord;
  221.                 }
  222.                 else
  223.                     MultiLocations.Add(playerLoc[0], PlayerCoord);
  224.             }
  225.         }
  226.  
  227.  
  228.     }
  229. }
  230.  
  231.  
  232. //Server Code
  233.  
  234.  
  235. using System;
  236. using System.Collections.Generic;
  237. using System.ComponentModel;
  238. using System.Data;
  239. using System.Drawing;
  240. using System.Linq;
  241. using System.Text;
  242. using System.Windows.Forms;
  243. using System.Threading;
  244. using System.Collections;
  245. using System.Net.Sockets;
  246. //using MySql.Data.MySqlClient;
  247.  
  248. namespace AxiomTestServer_Alpha_0_02
  249. {
  250.     public partial class mainForm : Form
  251.     {
  252.         static void Main()
  253.         {
  254.             Application.Run(new mainForm());
  255.         }
  256.  
  257.         public mainForm()
  258.         {
  259.             InitializeComponent();
  260.         }
  261.         delegate void SetTextCallback(string text);
  262.  
  263.  
  264.         const int PORT_NUM = 65000;
  265.         const int UDP_PORT = 65002;
  266.         private Hashtable clients = new Hashtable();
  267.         private TcpListener listener;
  268.         private Thread listenerThread;
  269.         //private UdpClient transmitter = new UdpClient(65002);
  270.         private Thread transThread;
  271.         Socket trans = new Socket(AddressFamily.InterNetwork,
  272.                     SocketType.Dgram, ProtocolType.Udp);
  273.         int LocCount = 0;
  274.        
  275.         private void ConnectUser(string userName, UserConnection sender)
  276.         {
  277.             if (clients.Contains(userName))
  278.             {
  279.                 ReplyToSender("REFUSE", sender);
  280.             }
  281.  
  282.             else
  283.             {
  284.                 sender.Name = userName;
  285.                 UpdateStatus(sender.Name + " has joined the chat");
  286.                 clients.Add(userName, sender);
  287.                 JoinSender(sender);
  288.                 SendToClients("CHAT|" + sender.Name + " has joined the chat.", sender);
  289.             }
  290.         }
  291.  
  292.         private void JoinSender(UserConnection sender)
  293.         {
  294.             sender.Join();
  295.         }
  296.         private void DisconnectUser(UserConnection sender)
  297.         {
  298.             UpdateStatus(sender.Name + " has left the chat.");
  299.             SendToClients("CHAT|" + sender.Name + " has left the chat.", sender);
  300.             clients.Remove(sender.Name);
  301.         }
  302.  
  303.         private void ConnectionListen()
  304.         {
  305.             try
  306.             {
  307.                 listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM);
  308.                 listener.Start();
  309.  
  310.                 do
  311.                 {
  312.                     UserConnection client = new UserConnection(listener.AcceptTcpClient());
  313.                     client.LineRecieved += new LineRecieve(OnLineRecieved);
  314.                     UpdateStatus("Someone is attempting a login");
  315.  
  316.                 } while (true);
  317.             }
  318.             catch
  319.             {
  320.             }
  321.         }
  322.  
  323.         private void OnLineRecieved(UserConnection sender, string data)
  324.         {
  325.             string[] dataArray;
  326.  
  327.             dataArray = data.Split((char)124);
  328.  
  329.             switch (dataArray[0])
  330.             {
  331.                 case "CONNECT":
  332.                     ConnectUser(dataArray[1], sender);
  333.                     break;
  334.                 case "CHAT":
  335.                     SendChat(dataArray[1], sender);
  336.                     break;
  337.                 case "DISCONNECT":
  338.                     DisconnectUser(sender);
  339.                     break;
  340.                 case "UPDATEPOS":
  341.                     UpdateStatus("Client is updating the position");
  342.                     UpdatePos(sender, dataArray[1]);
  343.                     break;
  344.                  default:
  345.                     //let the users know this message was sent wrong
  346.                     break;
  347.             }
  348.        
  349.         }
  350.  
  351.        
  352.         private void UpdatePos(UserConnection sender, string data)
  353.         {
  354.             string[] dataArr = data.Split(',');
  355.  
  356.             sender.UpdateLocation(dataArr);
  357.  
  358.             if(LocCount == 3)
  359.             {
  360.                 string message = "UPDATEPOS|";
  361.                 UserConnection client;
  362.                 foreach (DictionaryEntry entry in clients)
  363.                 {
  364.                     client = (UserConnection)entry.Value;
  365.                     message += client.Name + "," + client.Location.PosX + "," + client.Location.PosY + "," + client.Location.PosZ + "," + client.Location.RotX + "," +
  366.                         client.Location.RotY + "," + client.Location.RotZ + "|";
  367.                 }
  368.  
  369.                 foreach (DictionaryEntry entry in clients)
  370.                 {
  371.                     client = (UserConnection)entry.Value;
  372.  
  373.                     client.SendData(message,trans);
  374.                 }
  375.                 LocCount = 0;
  376.                
  377.             }
  378.             LocCount++;
  379.         }
  380.  
  381.         private void receiveUDP()
  382.         {
  383.             System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT);
  384.             System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
  385.             trans.ExclusiveAddressUse = true;
  386.             trans.Bind(serverIP);
  387.             System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
  388.             System.Net.EndPoint Remote = (System.Net.EndPoint)ipep;
  389.            
  390.             while (true)
  391.             {
  392.                
  393.                 byte[] content = new byte[1024];
  394.                
  395.                 int recv = trans.ReceiveFrom(content,ref Remote);
  396.  
  397.                 int portNum = ((System.Net.IPEndPoint)Remote).Port;
  398.                 string message = Encoding.ASCII.GetString(content);
  399.                 string[] data = message.Split((char)124);
  400.                 //UpdateStatus(data[0] + data[1]);
  401.  
  402.                 UserConnection sender = (UserConnection)clients[data[0]];
  403.                 if (sender.PortNumber != portNum)
  404.                     sender.PortNumber = portNum;
  405.                
  406.                 sender.RemoteEnd = Remote;
  407.                
  408.                 if (data.Length > 2)
  409.                 {
  410.                     OnLineRecieved(sender, data[1] + "|" + data[2]);
  411.                 }
  412.                 else
  413.                 {
  414.                     OnLineRecieved(sender, data[1]);
  415.                 }
  416.             }
  417.         }
  418.  
  419.         private void mainForm_Load(object sender, EventArgs e)
  420.         {
  421.             listenerThread = new Thread(ConnectionListen);
  422.             listenerThread.IsBackground = true;
  423.             listenerThread.Start();
  424.  
  425.             transThread = new Thread(receiveUDP);
  426.             transThread.IsBackground = true;
  427.             transThread.Start();
  428.             UpdateStatus("Server Started");
  429.  
  430.         }
  431.  
  432.         private void SendToClients(string message, UserConnection sender)
  433.         {
  434.             UserConnection client;
  435.  
  436.             foreach (DictionaryEntry entry in clients)
  437.             {
  438.                 client = (UserConnection)entry.Value;
  439.  
  440.                 if (client.Name != sender.Name)
  441.                 {
  442.                     client.SendData(message,trans);
  443.                 }
  444.             }
  445.         }
  446.  
  447.         private void SendChat(string message, UserConnection sender)
  448.         {
  449.             SendToClients("CHAT|" + sender.Name + ": " + message, sender);
  450.             UpdateStatus(sender.Name + ": " + message);
  451.         }
  452.  
  453.         private void ReplyToSender(string message, UserConnection sender)
  454.         {
  455.             sender.SendData(message,trans);
  456.         }
  457.  
  458.         private void Broadcast(string message)
  459.         {
  460.             UserConnection client;
  461.  
  462.             foreach (DictionaryEntry entry in clients)
  463.             {
  464.                 client = (UserConnection)entry.Value;
  465.                 client.SendData("BROAD|" + message,trans);
  466.             }
  467.         }
  468.  
  469.         private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
  470.         {
  471.             transThread.Abort();
  472.             listenerThread.Abort();
  473.             //transmitter.Close();
  474.             listener.Stop();
  475.             clients.Clear();
  476.         }
  477.  
  478.         public void UpdateStatus(string message)
  479.         {
  480.             if (this.textBox1.InvokeRequired)
  481.             {
  482.                 SetTextCallback d = new SetTextCallback(UpdateStatus);
  483.                 this.Invoke(d, new object[] { message });
  484.             }
  485.             else
  486.             {
  487.                 this.textBox1.AppendText(message);
  488.             }
  489.         }
  490.  
  491.         private void button2_Click(object sender, EventArgs e)
  492.         {
  493.             if (textBox2.TextLength > 0)
  494.             {
  495.                 Broadcast(textBox2.Text.ToString());
  496.                 textBox2.Clear();
  497.             }
  498.         }
  499.        
  500.     }
  501. }
  502.  
  503.  
  504. //UserConnection Class
  505.  
  506. using System;
  507. using System.Collections.Generic;
  508. using System.Linq;
  509. using System.Text;
  510. using System.Net;
  511. using System.Net.Sockets;
  512. using System.IO;
  513. using System.Threading;
  514. using System.Windows.Forms;
  515.  
  516. namespace AxiomTestServer_Alpha_0_02
  517. {
  518.         public struct PlayerLoc
  519.         {
  520.             public string PosX;
  521.             public string PosY;
  522.             public string PosZ;
  523.             public string RotX;
  524.             public string RotY;
  525.             public string RotZ;
  526.         };
  527.  
  528.     public delegate void LineRecieve(UserConnection sender, string data);
  529.  
  530.     public class UserConnection
  531.     {
  532.         const int READ_BUFFER_SIZE = 255;
  533.         private TcpClient client;
  534.         private byte[] readBuffer = new byte[READ_BUFFER_SIZE];
  535.         private string strName;
  536.         public EndPoint RemoteEnd;
  537.         public IPEndPoint ipep;
  538.         public int PortNumber;
  539.         IPAddress ipAdd;
  540.         //Socket trans = new Socket(AddressFamily.InterNetwork,
  541.                      //SocketType.Dgram, ProtocolType.Udp);
  542.        
  543.         public PlayerLoc Location = new PlayerLoc();
  544.  
  545.         public UserConnection(TcpClient client)
  546.         {
  547.             this.client = client;
  548.             ipAdd = IPAddress.Parse(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
  549.            
  550.             this.client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null);
  551.         }
  552.        
  553.         public string Name
  554.         {
  555.             get
  556.             {
  557.                 return strName;
  558.             }
  559.  
  560.             set
  561.             {
  562.                 strName = value;
  563.             }
  564.         }
  565.  
  566.         public event LineRecieve LineRecieved;
  567.  
  568.  
  569.         public void Join()
  570.         {
  571.             StreamWriter writer = new StreamWriter(client.GetStream());
  572.             writer.Write("JOIN");
  573.             writer.Flush();
  574.         }
  575.         public void SendData(string data, Socket trans)
  576.         {
  577.             if (PortNumber != null)
  578.             {
  579.                 //ipep = new IPEndPoint(IPAddress.Any, PortNumber);
  580.                
  581.                 byte[] dataArr = Encoding.ASCII.GetBytes(data);
  582.  
  583.                 trans.SendTo(dataArr, dataArr.Length, SocketFlags.None, RemoteEnd);
  584.             }
  585.         }
  586.  
  587.        public void UpdateLocation(string[] data)
  588.        {
  589.            if (data.Length > 6)
  590.                return;
  591.            else
  592.            {
  593.                Location.PosX = data[0];
  594.                Location.PosY = data[1];
  595.                Location.PosZ = data[2];
  596.                Location.RotX = data[3];
  597.                Location.RotY = data[4];
  598.                Location.RotZ = data[5];
  599.            }
  600.  
  601.        }    
  602.            
  603.  
  604.        public void StreamReciever(IAsyncResult ar)
  605.        {
  606.            int bytesRead;
  607.            string strMessage;
  608.  
  609.            try
  610.            {
  611.                lock (client.GetStream())
  612.                {
  613.                    bytesRead = client.GetStream().EndRead(ar);
  614.                }
  615.  
  616.                strMessage = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
  617.                LineRecieved(this, strMessage);
  618.  
  619.                lock (client.GetStream())
  620.                {
  621.                    client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null);
  622.                }
  623.            }
  624.            catch (Exception e)
  625.            {
  626.                MessageBox.Show(e.Message.ToString());
  627.            }
  628.        }
  629.    
  630.      
  631.     }
  632. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement