Guest User

Untitled

a guest
Nov 21st, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.30 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.Networking;
  4. using UnityEngine.UI;
  5. using System.Text;
  6.  
  7. public class Player {
  8. public string playerName;
  9. public GameObject avatar;
  10. public int connectionId;
  11. }
  12.  
  13. public class Client : MonoBehaviour {
  14.  
  15. private const int MAX_CONNECTION = 10;
  16. private int port = 5701;
  17.  
  18. private int hostId;
  19. private int webHostId;
  20.  
  21. private int reliableChannel;
  22. private int unreliableChannel;
  23.  
  24. private int ourClientId;
  25. private int connectionId;
  26.  
  27. private float connectionTime;
  28. private bool isConnected = false;
  29. private bool isStarted = false;
  30. private byte error;
  31.  
  32. private string playerName;
  33.  
  34. public GameObject playerPrefab; // to Add player to the client
  35. public Dictionary<int,Player> players = new Dictionary<int, Player>();
  36.  
  37. public void Connect() {
  38. // Does the player have a name ?
  39. string pName = GameObject.Find("NameInput").GetComponent<InputField>().text; // get Text from InputField
  40. if (pName == "")
  41. {
  42. Debug.Log("You must enter a name");
  43. return;
  44.  
  45. }
  46. playerName = pName;
  47.  
  48. NetworkTransport.Init();
  49. ConnectionConfig cc = new ConnectionConfig();
  50.  
  51. reliableChannel = cc.AddChannel(QosType.Reliable);
  52. unreliableChannel = cc.AddChannel(QosType.Unreliable);
  53.  
  54. HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
  55.  
  56. hostId = NetworkTransport.AddHost(topo, 0);
  57. //hostId = NetworkTransport.AddWebsocketHost(topo, 0);
  58. connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);//"127.0.0.1 is local host IP"
  59.  
  60. connectionTime = Time.time;
  61. isConnected = true;
  62.  
  63. }
  64.  
  65.  
  66. private void Update() {
  67. if (!isConnected)
  68. return;
  69.  
  70.  
  71. int recHostId;
  72. int connectionId;
  73. int channelId;
  74. byte[] recBuffer = new byte[1024];
  75. int bufferSize = 1024;
  76. int dataSize;
  77. byte error;
  78. NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
  79. switch (recData) {
  80.  
  81. case NetworkEventType.DataEvent:
  82. string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
  83. Debug.Log("Receiving: " + msg);
  84. string[] splitData = msg.Split('|');
  85.  
  86. switch (splitData[0]) {
  87. case "ASKNAME":
  88. OnAskName(splitData);
  89. break;
  90. case "CNN":
  91. SpawnPlayer(splitData[1], int.Parse(splitData[2]));
  92. break;
  93. case "DC":
  94. PlayerDisconnected(int.Parse(splitData[1]));
  95. break;
  96. case "ASKPOSITION":
  97. OnAskPosition(splitData);
  98. break;
  99.  
  100. default:
  101. Debug.Log("Invalid message: " + msg);
  102. break;
  103. }
  104.  
  105. break;
  106. }
  107.  
  108. }
  109.  
  110. private void OnAskName(string[] data)
  111. {
  112. // Set this client's ID
  113. ourClientId = int.Parse(data[1]);
  114.  
  115. // Send our name to the server
  116. Send("NAMEIS|" + playerName, reliableChannel);
  117.  
  118. // Create all the other players
  119. for(int i = 2; i < data.Length - 1; i++) {
  120. string[] d = data[i].Split('%');
  121. SpawnPlayer(d[0], int.Parse(d[1]));
  122.  
  123. }
  124. }
  125.  
  126. private void SpawnPlayer(string playerName, int cnnId) {
  127. GameObject go = Instantiate(playerPrefab) as GameObject;
  128. // Is this ours?
  129. if (cnnId == ourClientId) {
  130. // Add mobility
  131. go.AddComponent<PlayerMotor>(); // Add script Motor
  132. GameObject.Find("Canvas").SetActive(false);
  133. GameObject.Find("Main Camera").SetActive(false);
  134. isStarted = true;
  135. }
  136.  
  137. Player p = new Player();
  138. p.avatar = go;
  139. p.playerName = playerName;
  140. p.connectionId = cnnId;
  141. p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
  142. players.Add(cnnId, p);
  143.  
  144. **if (cnnId == ourClientId) {
  145. p.avatar.GetComponentInChildren<Cemara>().enabled = true;
  146.  
  147. }else {
  148. p.avatar.GetComponentInChildren<Cemara>().enabled = false;
  149. }**
  150.  
  151. }
  152.  
  153. private void Send(string message, int channelId) {
  154. Debug.Log("Sending : " + message);
  155. byte[] msg = Encoding.Unicode.GetBytes(message);
  156. NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
  157. }
  158.  
  159. private void PlayerDisconnected(int cnnId) {
  160. Destroy(players[cnnId].avatar);
  161. players.Remove(cnnId);
  162. }
  163.  
  164. private void OnAskPosition(string[] data) {
  165. if (!isStarted)
  166. return;
  167.  
  168.  
  169. for (int i = 1; i <= data.Length-1;i++) // update positions of all players
  170. {
  171. string[] d = data[i].Split('%');
  172.  
  173. // Prevent the server from updating us
  174. if(ourClientId != int.Parse(d[0])) {
  175. Vector3 position = Vector3.zero;
  176. position.x = float.Parse(d[1]);
  177. position.y = float.Parse(d[2]);
  178. position.z = float.Parse(d[3]);
  179. Debug.Log(position.z);
  180. players[int.Parse(d[0])].avatar.transform.position = position;
  181. }
  182. }
  183. // Send our own position
  184. Vector3 myPosition = players[ourClientId].avatar.transform.position;
  185. string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString() + '|' + myPosition.z.ToString();
  186. Send(m, unreliableChannel);
  187. }
  188. }
  189.  
  190. using System.Collections.Generic;
  191. using UnityEngine;
  192. using UnityEngine.Networking;
  193. using UnityEngine.UI;
  194. using System.Text;
  195.  
  196. public class Player {
  197. public string playerName;
  198. public GameObject avatar;
  199. public int connectionId;
  200. }
  201.  
  202. public class Client : MonoBehaviour {
  203.  
  204. private const int MAX_CONNECTION = 10;
  205. private int port = 5701;
  206.  
  207. private int hostId;
  208. private int webHostId;
  209.  
  210. private int reliableChannel;
  211. private int unreliableChannel;
  212.  
  213. private int ourClientId;
  214. private int connectionId;
  215.  
  216. private float connectionTime;
  217. private bool isConnected = false;
  218. private bool isStarted = false;
  219. private byte error;
  220.  
  221. private string playerName;
  222.  
  223. public GameObject playerPrefab; // to Add player to the client
  224. public Dictionary<int,Player> players = new Dictionary<int, Player>();
  225.  
  226. public void Connect() {
  227. // Does the player have a name ?
  228. string pName = GameObject.Find("NameInput").GetComponent<InputField>().text; // get Text from InputField
  229. if (pName == "")
  230. {
  231. Debug.Log("You must enter a name");
  232. return;
  233.  
  234. }
  235. playerName = pName;
  236.  
  237. NetworkTransport.Init();
  238. ConnectionConfig cc = new ConnectionConfig();
  239.  
  240. reliableChannel = cc.AddChannel(QosType.Reliable);
  241. unreliableChannel = cc.AddChannel(QosType.Unreliable);
  242.  
  243. HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
  244.  
  245. hostId = NetworkTransport.AddHost(topo, 0);
  246. //hostId = NetworkTransport.AddWebsocketHost(topo, 0);
  247. connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);//"127.0.0.1 is local host IP"
  248.  
  249. connectionTime = Time.time;
  250. isConnected = true;
  251.  
  252. }
  253.  
  254.  
  255. private void Update() {
  256. if (!isConnected)
  257. return;
  258.  
  259.  
  260. int recHostId;
  261. int connectionId;
  262. int channelId;
  263. byte[] recBuffer = new byte[1024];
  264. int bufferSize = 1024;
  265. int dataSize;
  266. byte error;
  267. NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
  268. switch (recData) {
  269.  
  270. case NetworkEventType.DataEvent:
  271. string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
  272. Debug.Log("Receiving: " + msg);
  273. string[] splitData = msg.Split('|');
  274.  
  275. switch (splitData[0]) {
  276. case "ASKNAME":
  277. OnAskName(splitData);
  278. break;
  279. case "CNN":
  280. SpawnPlayer(splitData[1], int.Parse(splitData[2]));
  281. break;
  282. case "DC":
  283. PlayerDisconnected(int.Parse(splitData[1]));
  284. break;
  285. case "ASKPOSITION":
  286. OnAskPosition(splitData);
  287. break;
  288.  
  289. default:
  290. Debug.Log("Invalid message: " + msg);
  291. break;
  292. }
  293.  
  294. break;
  295. }
  296.  
  297. }
  298.  
  299. private void OnAskName(string[] data)
  300. {
  301. // Set this client's ID
  302. ourClientId = int.Parse(data[1]);
  303.  
  304. // Send our name to the server
  305. Send("NAMEIS|" + playerName, reliableChannel);
  306.  
  307. // Create all the other players
  308. for(int i = 2; i < data.Length - 1; i++) {
  309. string[] d = data[i].Split('%');
  310. SpawnPlayer(d[0], int.Parse(d[1]));
  311.  
  312. }
  313. }
  314.  
  315. private void SpawnPlayer(string playerName, int cnnId) {
  316. GameObject go = Instantiate(playerPrefab) as GameObject;
  317. // Is this ours?
  318. if (cnnId == ourClientId) {
  319. // Add mobility
  320. go.AddComponent<PlayerMotor>(); // Add script Motor
  321. GameObject.Find("Canvas").SetActive(false);
  322. GameObject.Find("Main Camera").SetActive(false);
  323. isStarted = true;
  324. }
  325.  
  326. Player p = new Player();
  327. p.avatar = go;
  328. p.playerName = playerName;
  329. p.connectionId = cnnId;
  330. p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
  331. players.Add(cnnId, p);
  332.  
  333. **if (cnnId == ourClientId) {
  334. p.avatar.GetComponentInChildren<Cemara>().enabled = true;
  335.  
  336. }else {
  337. p.avatar.GetComponentInChildren<Cemara>().enabled = false;
  338. }**
  339.  
  340. }
  341.  
  342. private void Send(string message, int channelId) {
  343. Debug.Log("Sending : " + message);
  344. byte[] msg = Encoding.Unicode.GetBytes(message);
  345. NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
  346. }
  347.  
  348. private void PlayerDisconnected(int cnnId) {
  349. Destroy(players[cnnId].avatar);
  350. players.Remove(cnnId);
  351. }
  352.  
  353. private void OnAskPosition(string[] data) {
  354. if (!isStarted)
  355. return;
  356.  
  357.  
  358. for (int i = 1; i <= data.Length-1;i++) // update positions of all players
  359. {
  360. string[] d = data[i].Split('%');
  361.  
  362. // Prevent the server from updating us
  363. if(ourClientId != int.Parse(d[0])) {
  364. Vector3 position = Vector3.zero;
  365. position.x = float.Parse(d[1]);
  366. position.y = float.Parse(d[2]);
  367. position.z = float.Parse(d[3]);
  368. Debug.Log(position.z);
  369. players[int.Parse(d[0])].avatar.transform.position = position;
  370. }
  371. }
  372. // Send our own position
  373. Vector3 myPosition = players[ourClientId].avatar.transform.position;
  374. string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString() + '|' + myPosition.z.ToString();
  375. Send(m, unreliableChannel);
  376. }
  377. }
  378.  
  379. using System.Collections;
  380. using System.Collections.Generic;
  381. using System.Text;
  382. using UnityEngine;
  383. using UnityEngine.Networking;
  384.  
  385. public class ServerClient {
  386. public int connectionId;
  387. public string playerName;
  388. public Vector3 position;
  389. }
  390.  
  391. public class Server : MonoBehaviour {
  392.  
  393. private const int MAX_CONNECTION = 10;
  394. private int port = 5701;
  395.  
  396. private int hostId;
  397. private int webHostId;
  398.  
  399. private int reliableChannel;
  400. private int unreliableChannel;
  401.  
  402. private bool isStarted = false;
  403. private byte error;
  404.  
  405. private List<ServerClient> clients = new List<ServerClient>();
  406.  
  407. private float lastMovementUpdate;
  408. private float movementUpdataRate = 0.05f;
  409.  
  410.  
  411. private void Start() {
  412. NetworkTransport.Init();
  413. ConnectionConfig cc = new ConnectionConfig();
  414.  
  415. reliableChannel = cc.AddChannel(QosType.Reliable);
  416. unreliableChannel = cc.AddChannel(QosType.Unreliable);
  417.  
  418. HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
  419.  
  420. hostId = NetworkTransport.AddHost(topo, port, null); // null means that server accepts every IPs to connect to it.
  421. //hostId = NetworkTransport.AddWebsocketHost(topo, port, null);
  422.  
  423. isStarted = true;
  424. }
  425.  
  426. private void Update()
  427. {
  428. if (!isStarted)
  429. return;
  430.  
  431. int recHostId;
  432. int connectionId;
  433. int channelId;
  434. byte[] recBuffer = new byte[1024];
  435. int bufferSize = 1024;
  436. int dataSize;
  437. byte error;
  438. NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
  439. switch (recData) {
  440. case NetworkEventType.ConnectEvent: //2
  441. Debug.Log("Player " + connectionId + "has connected");
  442. OnConnection(connectionId);
  443. break;
  444.  
  445. case NetworkEventType.DataEvent: //3
  446. string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
  447. Debug.Log("Receiving from " + connectionId + ":" + msg);
  448. string[] splitData = msg.Split('|');
  449.  
  450. switch (splitData[0]) {
  451. case "NAMEIS":
  452. OnNameIs(connectionId, splitData[1]);
  453. break;
  454. case "MYPOSITION":
  455. OnMyPosition(connectionId, float.Parse(splitData[1]), float.Parse(splitData[2]), float.Parse(splitData[3]));
  456. break;
  457.  
  458. default:
  459. Debug.Log("Invalid message: " + msg);
  460. break;
  461. }
  462. break;
  463.  
  464. case NetworkEventType.DisconnectEvent: //4
  465. Debug.Log("Player " + connectionId + "has disconnected");
  466. OnDisconnection(connectionId);
  467. break;
  468. }
  469. //Ask player for their position
  470. if (Time.time - lastMovementUpdate > movementUpdataRate)
  471. {
  472. lastMovementUpdate = Time.time;
  473. string m = "ASKPOSITION|";
  474. foreach (ServerClient sc in clients)
  475. m += sc.connectionId.ToString() + '%' + sc.position.x.ToString() + '%' + sc.position.y.ToString() +'%'+ sc.position.z.ToString() + '|';
  476. m = m.Trim('|');
  477.  
  478. Send(m, unreliableChannel, clients);
  479. }
  480.  
  481. }
  482. private void OnConnection(int cnnId) {
  483. // Add him to a list
  484. ServerClient c = new ServerClient();
  485. c.connectionId = cnnId;
  486. c.playerName = "TEMP";
  487. clients.Add(c);
  488.  
  489. // when the player joins the server, tell him his ID
  490. // Request his name and send the name of all the other players
  491. string msg = "ASKNAME|" + cnnId + "|";
  492.  
  493. foreach (ServerClient sc in clients) {
  494. msg += sc.playerName + "%" + sc.connectionId + "|";
  495. }
  496.  
  497. msg = msg.Trim('|');
  498. Send(msg, reliableChannel, cnnId);
  499. }
  500.  
  501. private void Send(string message, int channelId, int cnnId) {
  502. List<ServerClient> c = new List<ServerClient>();
  503. c.Add(clients.Find(x => x.connectionId == cnnId));
  504. Send(message, channelId, c);
  505. }
  506.  
  507. private void Send(string message, int channelId, List<ServerClient> c) {
  508. Debug.Log("Sending : " + message);
  509. byte[] msg = Encoding.Unicode.GetBytes(message);
  510. foreach (ServerClient sc in c) {
  511. NetworkTransport.Send(hostId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
  512. }
  513.  
  514. }
  515.  
  516. private void OnNameIs(int cnnId, string PlayerName) {
  517. // Link the name to the connenction Id
  518. clients.Find(x => x.connectionId == cnnId).playerName = PlayerName;
  519. // Tell everybody that a new player has connected
  520. Send("CNN|" + PlayerName + '|' + cnnId, reliableChannel, clients);
  521. }
  522.  
  523. private void OnDisconnection(int cnnId) {
  524. //Remove this plyer from our client list
  525. clients.Remove(clients.Find(x => x.connectionId == cnnId));
  526.  
  527. //Tell everyone that somebody else has disconnected
  528. Send("DC|" + cnnId, reliableChannel, clients);
  529.  
  530. }
  531.  
  532. private void OnMyPosition(int cnnId, float x, float y, float z) {
  533. clients.Find(c => c.connectionId == cnnId).position = new Vector3(x, y, z);
  534. }
  535.  
  536. }
Add Comment
Please, Sign In to add comment