//Client Connection Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.IO; using UnityEngine; using System.Collections; namespace Axiom_ClientConnection_0_01 { public class Connector { const int READ_BUFFER_SIZE = 255; const int TCP_PORT_NUMBER = 65000; const int UDP_PORT_NUMBER = 65002; private TcpClient connectionClient; public Hashtable MultiLocations = new Hashtable(); public struct PlayerLocations { public Vector3 Position; public Quaternion Rotation; }; //UdpClient transmissionClient; private byte[] readbuffer = new byte[READ_BUFFER_SIZE]; public string message = ""; public string result = ""; private string username; IPAddress ipAddress; IPEndPoint servIP, listenUDP; Thread UDPListenerThread; int portNum = new int(); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); public bool CONNECTED = false; public int x = 0; public Connector() { } public string ConnectionAttempt(string ServeIP, string PlayUsername) { username = PlayUsername; try { connectionClient = new TcpClient(ServeIP,TCP_PORT_NUMBER); connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null); Login(username); ipAddress = IPAddress.Parse(((IPEndPoint)connectionClient.Client.RemoteEndPoint).Address.ToString()); servIP = new IPEndPoint(ipAddress,65002); listenUDP = new IPEndPoint(ipAddress, 0); UDPListenerThread = new Thread(receiveUDP); UDPListenerThread.IsBackground = true; UDPListenerThread.Start(); return "Connection Succeeded"; } catch(Exception ex) { return (ex.Message.ToString() + "Connection Failed"); } } private void receiveUDP() { System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT_NUMBER); System.Net.EndPoint serverIP = (System.Net.EndPoint)test; server.Bind(serverIP); EndPoint RemoteServ = (EndPoint)listenUDP; do { byte[] content = new byte[1024]; int data = server.ReceiveFrom(content, ref RemoteServ); string message = Encoding.ASCII.GetString(content); ProcessCommands(message); } while (true); } public void Login(string username) { StreamWriter writer = new StreamWriter(connectionClient.GetStream()); writer.Write("CONNECT|" + username); writer.Flush(); //connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null); } public void SendChat(string data) { SendData(username + "|CHAT|" + data); } public void SendUpdateLocation(string data) { SendData(username + "|UPDATEPOS|" + data); } public void Disconnect() { SendData(username + "|DISCONNECT|"); //StreamWriter writer = new StreamWriter(connectionClient.GetStream()); //writer.Write("DISCONNECT"); //writer.Flush(); server.Close(); UDPListenerThread.Abort(); connectionClient.Close(); } private void DoRead(IAsyncResult ar) { int BytesRead; try { BytesRead = connectionClient.GetStream().EndRead(ar); if (BytesRead < 1) { result = "DISCONNECTED"; return; } string message = Encoding.ASCII.GetString(readbuffer, 0, BytesRead); ProcessCommands(message); connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null); } catch { } } private void SendData(string data) { //result = data; byte[] dataArr = Encoding.ASCII.GetBytes(data); try { EndPoint servEnd = (EndPoint)servIP; //UDPListenerThread.Suspend(); server.SendTo(dataArr, dataArr.Length,SocketFlags.None, servEnd); //UDPListenerThread.Resume(); } catch (Exception e) { } } private void ProcessCommands(string data) { string[] dataArr; dataArr = data.Split((char)124); switch (dataArr[0]) { case "JOIN": result = "You have joined the chat!"; CONNECTED = true; break; case "CHAT": result = dataArr[1].ToString(); break; case "REFUSE": Login(username); result = "Connection refused. Attempting another login."; break; case "BROAD": result = "SERVER MESSAGE: " + dataArr[1].ToString(); break; case "UPDATEPOS": UpdateLoc(dataArr); //x++; break; default: result = "Server sent bad message waiting for retry"; break; } } private void UpdateLoc(string [] data) { //result = x.ToString(); string [] playerLoc; for (int i = 1; i < data.Length; i++) { playerLoc = data[i].Split(','); PlayerLocations PlayerCoord = new PlayerLocations(); Vector3 trans1; Quaternion trans2 = new Quaternion(); trans1.x = float.Parse(playerLoc[1]); trans1.y = float.Parse(playerLoc[2]); trans1.z = float.Parse(playerLoc[3]); trans2.x = float.Parse(playerLoc[4]); trans2.y = float.Parse(playerLoc[5]); trans2.z = float.Parse(playerLoc[6]); PlayerCoord.Position = trans1; PlayerCoord.Rotation = trans2; if(MultiLocations.ContainsKey(playerLoc[0])) { MultiLocations[playerLoc[0]] = PlayerCoord; } else MultiLocations.Add(playerLoc[0], PlayerCoord); } } } } //Server Code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Collections; using System.Net.Sockets; //using MySql.Data.MySqlClient; namespace AxiomTestServer_Alpha_0_02 { public partial class mainForm : Form { static void Main() { Application.Run(new mainForm()); } public mainForm() { InitializeComponent(); } delegate void SetTextCallback(string text); const int PORT_NUM = 65000; const int UDP_PORT = 65002; private Hashtable clients = new Hashtable(); private TcpListener listener; private Thread listenerThread; //private UdpClient transmitter = new UdpClient(65002); private Thread transThread; Socket trans = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); int LocCount = 0; private void ConnectUser(string userName, UserConnection sender) { if (clients.Contains(userName)) { ReplyToSender("REFUSE", sender); } else { sender.Name = userName; UpdateStatus(sender.Name + " has joined the chat"); clients.Add(userName, sender); JoinSender(sender); SendToClients("CHAT|" + sender.Name + " has joined the chat.", sender); } } private void JoinSender(UserConnection sender) { sender.Join(); } private void DisconnectUser(UserConnection sender) { UpdateStatus(sender.Name + " has left the chat."); SendToClients("CHAT|" + sender.Name + " has left the chat.", sender); clients.Remove(sender.Name); } private void ConnectionListen() { try { listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM); listener.Start(); do { UserConnection client = new UserConnection(listener.AcceptTcpClient()); client.LineRecieved += new LineRecieve(OnLineRecieved); UpdateStatus("Someone is attempting a login"); } while (true); } catch { } } private void OnLineRecieved(UserConnection sender, string data) { string[] dataArray; dataArray = data.Split((char)124); switch (dataArray[0]) { case "CONNECT": ConnectUser(dataArray[1], sender); break; case "CHAT": SendChat(dataArray[1], sender); break; case "DISCONNECT": DisconnectUser(sender); break; case "UPDATEPOS": UpdateStatus("Client is updating the position"); UpdatePos(sender, dataArray[1]); break; default: //let the users know this message was sent wrong break; } } private void UpdatePos(UserConnection sender, string data) { string[] dataArr = data.Split(','); sender.UpdateLocation(dataArr); if(LocCount == 3) { string message = "UPDATEPOS|"; UserConnection client; foreach (DictionaryEntry entry in clients) { client = (UserConnection)entry.Value; message += client.Name + "," + client.Location.PosX + "," + client.Location.PosY + "," + client.Location.PosZ + "," + client.Location.RotX + "," + client.Location.RotY + "," + client.Location.RotZ + "|"; } foreach (DictionaryEntry entry in clients) { client = (UserConnection)entry.Value; client.SendData(message,trans); } LocCount = 0; } LocCount++; } private void receiveUDP() { System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT); System.Net.EndPoint serverIP = (System.Net.EndPoint)test; trans.ExclusiveAddressUse = true; trans.Bind(serverIP); System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); System.Net.EndPoint Remote = (System.Net.EndPoint)ipep; while (true) { byte[] content = new byte[1024]; int recv = trans.ReceiveFrom(content,ref Remote); int portNum = ((System.Net.IPEndPoint)Remote).Port; string message = Encoding.ASCII.GetString(content); string[] data = message.Split((char)124); //UpdateStatus(data[0] + data[1]); UserConnection sender = (UserConnection)clients[data[0]]; if (sender.PortNumber != portNum) sender.PortNumber = portNum; sender.RemoteEnd = Remote; if (data.Length > 2) { OnLineRecieved(sender, data[1] + "|" + data[2]); } else { OnLineRecieved(sender, data[1]); } } } private void mainForm_Load(object sender, EventArgs e) { listenerThread = new Thread(ConnectionListen); listenerThread.IsBackground = true; listenerThread.Start(); transThread = new Thread(receiveUDP); transThread.IsBackground = true; transThread.Start(); UpdateStatus("Server Started"); } private void SendToClients(string message, UserConnection sender) { UserConnection client; foreach (DictionaryEntry entry in clients) { client = (UserConnection)entry.Value; if (client.Name != sender.Name) { client.SendData(message,trans); } } } private void SendChat(string message, UserConnection sender) { SendToClients("CHAT|" + sender.Name + ": " + message, sender); UpdateStatus(sender.Name + ": " + message); } private void ReplyToSender(string message, UserConnection sender) { sender.SendData(message,trans); } private void Broadcast(string message) { UserConnection client; foreach (DictionaryEntry entry in clients) { client = (UserConnection)entry.Value; client.SendData("BROAD|" + message,trans); } } private void mainForm_FormClosing(object sender, FormClosingEventArgs e) { transThread.Abort(); listenerThread.Abort(); //transmitter.Close(); listener.Stop(); clients.Clear(); } public void UpdateStatus(string message) { if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(UpdateStatus); this.Invoke(d, new object[] { message }); } else { this.textBox1.AppendText(message); } } private void button2_Click(object sender, EventArgs e) { if (textBox2.TextLength > 0) { Broadcast(textBox2.Text.ToString()); textBox2.Clear(); } } } } //UserConnection Class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; using System.Windows.Forms; namespace AxiomTestServer_Alpha_0_02 { public struct PlayerLoc { public string PosX; public string PosY; public string PosZ; public string RotX; public string RotY; public string RotZ; }; public delegate void LineRecieve(UserConnection sender, string data); public class UserConnection { const int READ_BUFFER_SIZE = 255; private TcpClient client; private byte[] readBuffer = new byte[READ_BUFFER_SIZE]; private string strName; public EndPoint RemoteEnd; public IPEndPoint ipep; public int PortNumber; IPAddress ipAdd; //Socket trans = new Socket(AddressFamily.InterNetwork, //SocketType.Dgram, ProtocolType.Udp); public PlayerLoc Location = new PlayerLoc(); public UserConnection(TcpClient client) { this.client = client; ipAdd = IPAddress.Parse(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString()); this.client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null); } public string Name { get { return strName; } set { strName = value; } } public event LineRecieve LineRecieved; public void Join() { StreamWriter writer = new StreamWriter(client.GetStream()); writer.Write("JOIN"); writer.Flush(); } public void SendData(string data, Socket trans) { if (PortNumber != null) { //ipep = new IPEndPoint(IPAddress.Any, PortNumber); byte[] dataArr = Encoding.ASCII.GetBytes(data); trans.SendTo(dataArr, dataArr.Length, SocketFlags.None, RemoteEnd); } } public void UpdateLocation(string[] data) { if (data.Length > 6) return; else { Location.PosX = data[0]; Location.PosY = data[1]; Location.PosZ = data[2]; Location.RotX = data[3]; Location.RotY = data[4]; Location.RotZ = data[5]; } } public void StreamReciever(IAsyncResult ar) { int bytesRead; string strMessage; try { lock (client.GetStream()) { bytesRead = client.GetStream().EndRead(ar); } strMessage = Encoding.ASCII.GetString(readBuffer, 0, bytesRead); LineRecieved(this, strMessage); lock (client.GetStream()) { client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null); } } catch (Exception e) { MessageBox.Show(e.Message.ToString()); } } } }