Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lab-08/Assets/Scenes.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added Lab-08/Assets/Scenes/Scene2.unity
Binary file not shown.
8 changes: 8 additions & 0 deletions Lab-08/Assets/Scenes/Scene2.unity.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added Lab-08/Assets/Scenes/TestScene.unity
Binary file not shown.
8 changes: 8 additions & 0 deletions Lab-08/Assets/Scenes/TestScene.unity.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions Lab-08/Assets/Scripts.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

184 changes: 184 additions & 0 deletions Lab-08/Assets/Scripts/ClientConnection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
using UnityEngine;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.Networking;

public class ClientConnection : MonoBehaviour
{

int clientSocketID = -1;
//Will store the unique identifier of the session that keeps the connection between the client
//and the server. You use this ID as the 'target' when sending messages to the server.
int clientServerConnectionID = -1;
int maxConnections = 10;
byte unreliableChannelID;
byte reliableChannelID;
bool isClientConnected = false;

void Start()
{
DontDestroyOnLoad(this);

//Build the global config
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.ReactorModel = ReactorModel.FixRateReactor;
globalConfig.ThreadAwakeTimeout = 10;

//Build the channel config
ConnectionConfig connectionConfig = new ConnectionConfig();
reliableChannelID = connectionConfig.AddChannel(QosType.ReliableSequenced);
unreliableChannelID = connectionConfig.AddChannel(QosType.UnreliableSequenced);

//Create the host topology
HostTopology hostTopology = new HostTopology(connectionConfig, maxConnections);

//Initialize the network transport
//Open a socket for the client
NetworkTransport.Init(globalConfig);
clientSocketID = NetworkTransport.AddHost(hostTopology, 7778);

//Make sure the client created the socket successfully
if (clientSocketID < 0)
Debug.Log("Client socket creation failed");
else
Debug.Log("Client socket creation success");


//Create a byte to store a possible error
byte error;

//Connect to the server using
//int NetworkTransport.Connect(int socketConnectingFrom, string ipAddress, int port, 0, out byte possibleError)
//Store the ID of the connection in clientServerConnectionID
clientServerConnectionID = NetworkTransport.Connect(clientSocketID, Network.player.ipAddress.ToString(), 7777, 0, out error);

//Display the error (if it did error out)
if (error != (byte)NetworkError.Ok)
{
NetworkError networkError = (NetworkError)error;
Debug.Log("Error: " + networkError.ToString());
}
}

void Update()
{
//If the client failed to create the socket, leave this function
if (clientSocketID < 0)
return;

PollBasics();

//If the user pressed the Space key
if (Input.GetKeyDown(KeyCode.Space))
{
//Send a message to the server "FirstConnect"
SendMessage("FirstConnect");
}

//If the user pressed the R key
if (Input.GetKeyDown(KeyCode.R))
{
//Send a message to the server "Random message!"
SendMessage("Random message!");
}
}

void SendMessage(string message)
{
//create a byte to store a possible error
byte error;
//Create a buffer to store the message
byte[] buffer = new byte[1024];
//Create a memory stream to send the information through
MemoryStream memoryStream = new MemoryStream(buffer);
//Create a binary formatter to serialize and translate the message into binary
BinaryFormatter binaryFormatter = new BinaryFormatter();
//Serialize the message
binaryFormatter.Serialize(memoryStream, message);

//Send the message from this client, over the client server connection, using the reliable channel
NetworkTransport.Send(clientSocketID, clientServerConnectionID, reliableChannelID, buffer, 1024, out error);

//Display the error (if it did error out)
if (error != (byte)NetworkError.Ok)
{
NetworkError networkError = (NetworkError)error;
Debug.Log("Error: " + networkError.ToString());
}
}

void InterperateMessage(string message)
{
//if the message is "goto_NewScene"
if (message == "goto_Scene2")
{
//load the level named "Scene2"
Application.LoadLevel("Scene2");
}
}

void PollBasics()
{
//prepare to receive messages by practicing good bookkeeping
byte error;
byte[] buffer = new byte[1024];
int recHostID;
int connectionId;
int channelId;
int dataSize;

NetworkEventType networkEvent = NetworkEventType.DataEvent;
//do
do
{
//Receive network events
networkEvent = NetworkTransport.Receive(out recHostID, out connectionId, out channelId, buffer, 1024, out dataSize, out error);
//switch on the network event types
switch(networkEvent)
{
//if nothing, do nothing
case NetworkEventType.Nothing:
break;
//if connection
case NetworkEventType.ConnectEvent:
//verify that the message was meant for me
if(recHostID == clientSocketID)
{
//debug out that i connected to the server, and display the ID of what I connected to
Debug.Log("Client: Connected to server" + recHostID);
//set my bool that is keeping track if I am connected to a server to true
isClientConnected = true;
}
break;
//if data event
case NetworkEventType.DataEvent:
//verify that the message was meant for me and if I am connected to a server
if(recHostID == clientSocketID)
{
MemoryStream memoryStream = new MemoryStream(buffer);
BinaryFormatter binaryFormatter = new BinaryFormatter();
//decode the message (bring it through the memory stream, deseralize it, translate the binary)
string message = binaryFormatter.Deserialize(memoryStream).ToString();
//Debug the message and the connection that the message was sent from
Debug.Log("Client: Received data from " + connectionId.ToString() + ". Message: " + message);
InterperateMessage(message);
}
break;
//if disconnection
case NetworkEventType.DisconnectEvent:
//verify that the message was meant for me, and that I am disconnecting from the current connection I have with the server
if (recHostID == clientSocketID)
{
//debug that I disconnected
Debug.Log("Client: Connection lost");
//set my bool that is keeping track if I am connected to a server to false
isClientConnected = false;
}

break;
}
//while (the network event I am receiving is not Nothing)
} while (networkEvent != NetworkEventType.Nothing);
}
}
12 changes: 12 additions & 0 deletions Lab-08/Assets/Scripts/ClientConnection.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

132 changes: 132 additions & 0 deletions Lab-08/Assets/Scripts/ServerConnection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.Networking;

public class ServerConnection : MonoBehaviour {

int serverSocketID = -1;
int maxConnections = 10;
byte unreliableChannelID;
byte reliableChannelID;
bool serverInitilized = false;

// Use this for initialization
void Start () {
DontDestroyOnLoad(this);

GlobalConfig globalConfig = new GlobalConfig ();
globalConfig.ReactorModel = ReactorModel.FixRateReactor;
globalConfig.ThreadAwakeTimeout = 10;

ConnectionConfig connectionConfig = new ConnectionConfig ();
reliableChannelID = connectionConfig.AddChannel (QosType.ReliableSequenced);
unreliableChannelID = connectionConfig.AddChannel (QosType.UnreliableSequenced);

HostTopology hostTopology = new HostTopology (connectionConfig, maxConnections);

NetworkTransport.Init (globalConfig);
serverSocketID = NetworkTransport.AddHost (hostTopology, 7777);

if (serverSocketID < 0)
Debug.Log ("Server socket creation failed");
else
Debug.Log ("Server socket creation success");

serverInitilized = true;
}

// Update is called once per frame
void Update () {
if (!serverInitilized) {
return;
}

int recHostId; //who received the message
int connectionId; //who sent the message
int channelId; //what channel the message was sent from
int dataSize; //how large the message can be
byte[] buffer = new byte[1024]; //the actual message
byte error; //if there is an error

NetworkEventType networkEvent = NetworkEventType.DataEvent;

do {
networkEvent = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, buffer, 1024, out dataSize, out error);

switch(networkEvent)
{
case NetworkEventType.Nothing:
break;
case NetworkEventType.ConnectEvent:
//server received disconnect event
if(recHostId == serverSocketID){
Debug.Log ("Server: Player " + connectionId.ToString() + " connected");
}
break;
case NetworkEventType.DataEvent:
//Verify the server is the intended target^
if(recHostId == serverSocketID)
{
//open a memory stream with a size equal to the buffer we set up earlier
MemoryStream memoryStream = new MemoryStream(buffer);

//Create a binary formatter to begin reading the information from the member stream
BinaryFormatter binaryFormatter = new BinaryFormatter();

//utilize the binary formatter to deserialize the binary information stored i nthe memory string
//then convert that into a string
string message = binaryFormatter.Deserialize(memoryStream).ToString();

//debug out the message
Debug.Log("Server: Received Data from " + connectionId.ToString() + ". Message: " + message);

RespondMessage(message, connectionId);
}
break;
case NetworkEventType.DisconnectEvent:
//server received disconnect event
if(recHostId == serverSocketID)
{
Debug.Log("Server: Received disconnect from " + connectionId.ToString());
}
break;
}
} while (networkEvent != NetworkEventType.Nothing);
}

void SendMessage(string message, int target)
{
byte error;
byte[] buffer = new byte[1024];
MemoryStream memoryStream = new MemoryStream(buffer);
BinaryFormatter binaryFormatter = new BinaryFormatter();

binaryFormatter.Serialize(memoryStream, message);

//Who is sending, where to, what channel, what infor, how much infro, if there is an error
NetworkTransport.Send(serverSocketID, target, reliableChannelID, buffer, (int)memoryStream.Position, out error);

//error is always assigned and it uses ok to donate that there is nothing wrong
if(error != (byte)NetworkError.Ok)
{
NetworkError networkError = (NetworkError)error;
Debug.Log("Error: " + networkError.ToString());
}
}

void RespondMessage(string message, int playerID)
{
//Student will fill this out
if(message == "FirstConnect")
{
Debug.Log("First Conection: " + playerID);
}
SendMessage("goto_Scene2", playerID);
if(Application.loadedLevelName == "TestScene")
{
Application.LoadLevel("Scene2");
}
}
}
12 changes: 12 additions & 0 deletions Lab-08/Assets/Scripts/ServerConnection.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added Lab-08/ProjectSettings/AudioManager.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/DynamicsManager.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/EditorBuildSettings.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/EditorSettings.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/GraphicsSettings.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/InputManager.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/NavMeshAreas.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/NetworkManager.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/Physics2DSettings.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/ProjectSettings.asset
Binary file not shown.
2 changes: 2 additions & 0 deletions Lab-08/ProjectSettings/ProjectVersion.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
m_EditorVersion: 5.1.2f1
m_StandardAssetsVersion: 0
Binary file added Lab-08/ProjectSettings/QualitySettings.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/TagManager.asset
Binary file not shown.
Binary file added Lab-08/ProjectSettings/TimeManager.asset
Binary file not shown.
Binary file added Lab-08/builds/build1.exe
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added Lab-08/builds/build1_Data/Managed/System.dll
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading