Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Networking;
- using UnityEngine.UI;
- using System.Text;
- public class Player {
- public string playerName;
- public GameObject avatar;
- public int connectionId;
- }
- public class Client : MonoBehaviour {
- private const int MAX_CONNECTION = 10;
- private int port = 5701;
- private int hostId;
- private int webHostId;
- private int reliableChannel;
- private int unreliableChannel;
- private int ourClientId;
- private int connectionId;
- private float connectionTime;
- private bool isConnected = false;
- private bool isStarted = false;
- private byte error;
- private string playerName;
- public GameObject playerPrefab; // to Add player to the client
- public Dictionary<int,Player> players = new Dictionary<int, Player>();
- public void Connect() {
- // Does the player have a name ?
- string pName = GameObject.Find("NameInput").GetComponent<InputField>().text; // get Text from InputField
- if (pName == "")
- {
- Debug.Log("You must enter a name");
- return;
- }
- playerName = pName;
- NetworkTransport.Init();
- ConnectionConfig cc = new ConnectionConfig();
- reliableChannel = cc.AddChannel(QosType.Reliable);
- unreliableChannel = cc.AddChannel(QosType.Unreliable);
- HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
- hostId = NetworkTransport.AddHost(topo, 0);
- //hostId = NetworkTransport.AddWebsocketHost(topo, 0);
- connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);//"127.0.0.1 is local host IP"
- connectionTime = Time.time;
- isConnected = true;
- }
- private void Update() {
- if (!isConnected)
- return;
- int recHostId;
- int connectionId;
- int channelId;
- byte[] recBuffer = new byte[1024];
- int bufferSize = 1024;
- int dataSize;
- byte error;
- NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
- switch (recData) {
- case NetworkEventType.DataEvent:
- string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
- Debug.Log("Receiving: " + msg);
- string[] splitData = msg.Split('|');
- switch (splitData[0]) {
- case "ASKNAME":
- OnAskName(splitData);
- break;
- case "CNN":
- SpawnPlayer(splitData[1], int.Parse(splitData[2]));
- break;
- case "DC":
- PlayerDisconnected(int.Parse(splitData[1]));
- break;
- case "ASKPOSITION":
- OnAskPosition(splitData);
- break;
- default:
- Debug.Log("Invalid message: " + msg);
- break;
- }
- break;
- }
- }
- private void OnAskName(string[] data)
- {
- // Set this client's ID
- ourClientId = int.Parse(data[1]);
- // Send our name to the server
- Send("NAMEIS|" + playerName, reliableChannel);
- // Create all the other players
- for(int i = 2; i < data.Length - 1; i++) {
- string[] d = data[i].Split('%');
- SpawnPlayer(d[0], int.Parse(d[1]));
- }
- }
- private void SpawnPlayer(string playerName, int cnnId) {
- GameObject go = Instantiate(playerPrefab) as GameObject;
- // Is this ours?
- if (cnnId == ourClientId) {
- // Add mobility
- go.AddComponent<PlayerMotor>(); // Add script Motor
- GameObject.Find("Canvas").SetActive(false);
- GameObject.Find("Main Camera").SetActive(false);
- isStarted = true;
- }
- Player p = new Player();
- p.avatar = go;
- p.playerName = playerName;
- p.connectionId = cnnId;
- p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
- players.Add(cnnId, p);
- **if (cnnId == ourClientId) {
- p.avatar.GetComponentInChildren<Cemara>().enabled = true;
- }else {
- p.avatar.GetComponentInChildren<Cemara>().enabled = false;
- }**
- }
- private void Send(string message, int channelId) {
- Debug.Log("Sending : " + message);
- byte[] msg = Encoding.Unicode.GetBytes(message);
- NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
- }
- private void PlayerDisconnected(int cnnId) {
- Destroy(players[cnnId].avatar);
- players.Remove(cnnId);
- }
- private void OnAskPosition(string[] data) {
- if (!isStarted)
- return;
- for (int i = 1; i <= data.Length-1;i++) // update positions of all players
- {
- string[] d = data[i].Split('%');
- // Prevent the server from updating us
- if(ourClientId != int.Parse(d[0])) {
- Vector3 position = Vector3.zero;
- position.x = float.Parse(d[1]);
- position.y = float.Parse(d[2]);
- position.z = float.Parse(d[3]);
- Debug.Log(position.z);
- players[int.Parse(d[0])].avatar.transform.position = position;
- }
- }
- // Send our own position
- Vector3 myPosition = players[ourClientId].avatar.transform.position;
- string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString() + '|' + myPosition.z.ToString();
- Send(m, unreliableChannel);
- }
- }
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Networking;
- using UnityEngine.UI;
- using System.Text;
- public class Player {
- public string playerName;
- public GameObject avatar;
- public int connectionId;
- }
- public class Client : MonoBehaviour {
- private const int MAX_CONNECTION = 10;
- private int port = 5701;
- private int hostId;
- private int webHostId;
- private int reliableChannel;
- private int unreliableChannel;
- private int ourClientId;
- private int connectionId;
- private float connectionTime;
- private bool isConnected = false;
- private bool isStarted = false;
- private byte error;
- private string playerName;
- public GameObject playerPrefab; // to Add player to the client
- public Dictionary<int,Player> players = new Dictionary<int, Player>();
- public void Connect() {
- // Does the player have a name ?
- string pName = GameObject.Find("NameInput").GetComponent<InputField>().text; // get Text from InputField
- if (pName == "")
- {
- Debug.Log("You must enter a name");
- return;
- }
- playerName = pName;
- NetworkTransport.Init();
- ConnectionConfig cc = new ConnectionConfig();
- reliableChannel = cc.AddChannel(QosType.Reliable);
- unreliableChannel = cc.AddChannel(QosType.Unreliable);
- HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
- hostId = NetworkTransport.AddHost(topo, 0);
- //hostId = NetworkTransport.AddWebsocketHost(topo, 0);
- connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);//"127.0.0.1 is local host IP"
- connectionTime = Time.time;
- isConnected = true;
- }
- private void Update() {
- if (!isConnected)
- return;
- int recHostId;
- int connectionId;
- int channelId;
- byte[] recBuffer = new byte[1024];
- int bufferSize = 1024;
- int dataSize;
- byte error;
- NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
- switch (recData) {
- case NetworkEventType.DataEvent:
- string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
- Debug.Log("Receiving: " + msg);
- string[] splitData = msg.Split('|');
- switch (splitData[0]) {
- case "ASKNAME":
- OnAskName(splitData);
- break;
- case "CNN":
- SpawnPlayer(splitData[1], int.Parse(splitData[2]));
- break;
- case "DC":
- PlayerDisconnected(int.Parse(splitData[1]));
- break;
- case "ASKPOSITION":
- OnAskPosition(splitData);
- break;
- default:
- Debug.Log("Invalid message: " + msg);
- break;
- }
- break;
- }
- }
- private void OnAskName(string[] data)
- {
- // Set this client's ID
- ourClientId = int.Parse(data[1]);
- // Send our name to the server
- Send("NAMEIS|" + playerName, reliableChannel);
- // Create all the other players
- for(int i = 2; i < data.Length - 1; i++) {
- string[] d = data[i].Split('%');
- SpawnPlayer(d[0], int.Parse(d[1]));
- }
- }
- private void SpawnPlayer(string playerName, int cnnId) {
- GameObject go = Instantiate(playerPrefab) as GameObject;
- // Is this ours?
- if (cnnId == ourClientId) {
- // Add mobility
- go.AddComponent<PlayerMotor>(); // Add script Motor
- GameObject.Find("Canvas").SetActive(false);
- GameObject.Find("Main Camera").SetActive(false);
- isStarted = true;
- }
- Player p = new Player();
- p.avatar = go;
- p.playerName = playerName;
- p.connectionId = cnnId;
- p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
- players.Add(cnnId, p);
- **if (cnnId == ourClientId) {
- p.avatar.GetComponentInChildren<Cemara>().enabled = true;
- }else {
- p.avatar.GetComponentInChildren<Cemara>().enabled = false;
- }**
- }
- private void Send(string message, int channelId) {
- Debug.Log("Sending : " + message);
- byte[] msg = Encoding.Unicode.GetBytes(message);
- NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
- }
- private void PlayerDisconnected(int cnnId) {
- Destroy(players[cnnId].avatar);
- players.Remove(cnnId);
- }
- private void OnAskPosition(string[] data) {
- if (!isStarted)
- return;
- for (int i = 1; i <= data.Length-1;i++) // update positions of all players
- {
- string[] d = data[i].Split('%');
- // Prevent the server from updating us
- if(ourClientId != int.Parse(d[0])) {
- Vector3 position = Vector3.zero;
- position.x = float.Parse(d[1]);
- position.y = float.Parse(d[2]);
- position.z = float.Parse(d[3]);
- Debug.Log(position.z);
- players[int.Parse(d[0])].avatar.transform.position = position;
- }
- }
- // Send our own position
- Vector3 myPosition = players[ourClientId].avatar.transform.position;
- string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString() + '|' + myPosition.z.ToString();
- Send(m, unreliableChannel);
- }
- }
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Networking;
- public class ServerClient {
- public int connectionId;
- public string playerName;
- public Vector3 position;
- }
- public class Server : MonoBehaviour {
- private const int MAX_CONNECTION = 10;
- private int port = 5701;
- private int hostId;
- private int webHostId;
- private int reliableChannel;
- private int unreliableChannel;
- private bool isStarted = false;
- private byte error;
- private List<ServerClient> clients = new List<ServerClient>();
- private float lastMovementUpdate;
- private float movementUpdataRate = 0.05f;
- private void Start() {
- NetworkTransport.Init();
- ConnectionConfig cc = new ConnectionConfig();
- reliableChannel = cc.AddChannel(QosType.Reliable);
- unreliableChannel = cc.AddChannel(QosType.Unreliable);
- HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
- hostId = NetworkTransport.AddHost(topo, port, null); // null means that server accepts every IPs to connect to it.
- //hostId = NetworkTransport.AddWebsocketHost(topo, port, null);
- isStarted = true;
- }
- private void Update()
- {
- if (!isStarted)
- return;
- int recHostId;
- int connectionId;
- int channelId;
- byte[] recBuffer = new byte[1024];
- int bufferSize = 1024;
- int dataSize;
- byte error;
- NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
- switch (recData) {
- case NetworkEventType.ConnectEvent: //2
- Debug.Log("Player " + connectionId + "has connected");
- OnConnection(connectionId);
- break;
- case NetworkEventType.DataEvent: //3
- string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
- Debug.Log("Receiving from " + connectionId + ":" + msg);
- string[] splitData = msg.Split('|');
- switch (splitData[0]) {
- case "NAMEIS":
- OnNameIs(connectionId, splitData[1]);
- break;
- case "MYPOSITION":
- OnMyPosition(connectionId, float.Parse(splitData[1]), float.Parse(splitData[2]), float.Parse(splitData[3]));
- break;
- default:
- Debug.Log("Invalid message: " + msg);
- break;
- }
- break;
- case NetworkEventType.DisconnectEvent: //4
- Debug.Log("Player " + connectionId + "has disconnected");
- OnDisconnection(connectionId);
- break;
- }
- //Ask player for their position
- if (Time.time - lastMovementUpdate > movementUpdataRate)
- {
- lastMovementUpdate = Time.time;
- string m = "ASKPOSITION|";
- foreach (ServerClient sc in clients)
- m += sc.connectionId.ToString() + '%' + sc.position.x.ToString() + '%' + sc.position.y.ToString() +'%'+ sc.position.z.ToString() + '|';
- m = m.Trim('|');
- Send(m, unreliableChannel, clients);
- }
- }
- private void OnConnection(int cnnId) {
- // Add him to a list
- ServerClient c = new ServerClient();
- c.connectionId = cnnId;
- c.playerName = "TEMP";
- clients.Add(c);
- // when the player joins the server, tell him his ID
- // Request his name and send the name of all the other players
- string msg = "ASKNAME|" + cnnId + "|";
- foreach (ServerClient sc in clients) {
- msg += sc.playerName + "%" + sc.connectionId + "|";
- }
- msg = msg.Trim('|');
- Send(msg, reliableChannel, cnnId);
- }
- private void Send(string message, int channelId, int cnnId) {
- List<ServerClient> c = new List<ServerClient>();
- c.Add(clients.Find(x => x.connectionId == cnnId));
- Send(message, channelId, c);
- }
- private void Send(string message, int channelId, List<ServerClient> c) {
- Debug.Log("Sending : " + message);
- byte[] msg = Encoding.Unicode.GetBytes(message);
- foreach (ServerClient sc in c) {
- NetworkTransport.Send(hostId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
- }
- }
- private void OnNameIs(int cnnId, string PlayerName) {
- // Link the name to the connenction Id
- clients.Find(x => x.connectionId == cnnId).playerName = PlayerName;
- // Tell everybody that a new player has connected
- Send("CNN|" + PlayerName + '|' + cnnId, reliableChannel, clients);
- }
- private void OnDisconnection(int cnnId) {
- //Remove this plyer from our client list
- clients.Remove(clients.Find(x => x.connectionId == cnnId));
- //Tell everyone that somebody else has disconnected
- Send("DC|" + cnnId, reliableChannel, clients);
- }
- private void OnMyPosition(int cnnId, float x, float y, float z) {
- clients.Find(c => c.connectionId == cnnId).position = new Vector3(x, y, z);
- }
- }
Add Comment
Please, Sign In to add comment