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
Binary file added Lab 8 Report.docx
Binary file not shown.
9 changes: 9 additions & 0 deletions NETWORKING LAB 03/Assets/Scenes.meta

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

Binary file not shown.
8 changes: 8 additions & 0 deletions NETWORKING LAB 03/Assets/Scenes/DefaultScene.unity.meta

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

Binary file added NETWORKING LAB 03/Assets/Scenes/Scene2.unity
Binary file not shown.
8 changes: 8 additions & 0 deletions NETWORKING LAB 03/Assets/Scenes/Scene2.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 NETWORKING LAB 03/Assets/Scripts.meta

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

175 changes: 175 additions & 0 deletions NETWORKING LAB 03/Assets/Scripts/ClientConnection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
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
NetworkTransport.Init(globalConfig);

//Open a socket for the client
clientSocketID = NetworkTransport.AddHost (hostTopology, 7777);

//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, "127.0.0.1", 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
//Send a message to the server "FirstConnect"
if (Input.GetKey(KeyCode.Space))
SendMessage("FirstConnect");

//If the user pressed the R key
//Send a message to the server "Random message!"
if (Input.GetKey(KeyCode.R))
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
Stream 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, (int)memoryStream.Position, 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"
//load the level named "Scene2"
if (message == "goto_NewScene")
Application.LoadLevel("Scene2");
}

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

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: Server " + connectionId.ToString () + " connected!" );
}
//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) && isClientConnected)
{
//decode the message (bring it through the memory stream, deseralize it, translate the binary)
Stream memoryStream = new MemoryStream(buffer);
BinaryFormatter binaryFormatter = new BinaryFormatter();
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); //the message to interperate
}
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) && isClientConnected)
{
NetworkTransport.Disconnect(clientSocketID, connectionId, out error);
//debug that I disconnected
Debug.Log("Client: Disconnected from " + connectionId.ToString());
//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 NETWORKING LAB 03/Assets/Scripts/ClientConnection.cs.meta

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

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

public class ServerConnection : MonoBehaviour {
int serverSocketID = -1;
int maxConnections = 10;
byte unreliableChannelID;
byte reliableChannelID;
bool serverInitialized = 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");

serverInitialized = true;
}

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

int recHostId;
int connectionId;
int channelId;
int dataSize;
byte[] buffer = new byte[1024];
byte 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:
if( recHostId == serverSocketID )
{
Debug.Log ("Server: Player " + connectionId.ToString () + " connected!" );
}
break;
case NetworkEventType.DataEvent:
if( recHostId == serverSocketID )
{
Stream memoryStream = new MemoryStream(buffer);
BinaryFormatter binaryFormatter = new BinaryFormatter();
string message = binaryFormatter.Deserialize( memoryStream ).ToString ();
Debug.Log ("Server: Received Data from " + connectionId.ToString () + "! Message: " + message );
RespondMessage(message, connectionId);
}
break;
case NetworkEventType.DisconnectEvent:
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];
Stream memoryStream = new MemoryStream(buffer);
BinaryFormatter binaryFormatter = new BinaryFormatter();

binaryFormatter.Serialize (memoryStream, message);
NetworkTransport.Send (serverSocketID, target, reliableChannelID, buffer, (int)memoryStream.Position, out error);

if (error != (byte)NetworkError.Ok)
{
NetworkError networkError = (NetworkError) error;
Debug.Log ("Error: " + networkError.ToString ());
}
}

void RespondMessage(string message, int playerID)
{
if (message == "FirstConnect")
{
Debug.Log ("message was FirstConnect! from player " + playerID.ToString());
SendMessage("goto_NewScene", playerID);
if (Application.loadedLevelName != "Scene2")
Application.LoadLevel("Scene2");
}
}
}
12 changes: 12 additions & 0 deletions NETWORKING LAB 03/Assets/Scripts/ServerConnection.cs.meta

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

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions NETWORKING LAB 03/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 not shown.
Binary file not shown.
Binary file not shown.