Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Networking;
- public class UNetTest : MonoBehaviour
- {
- enum Status
- {
- Offline,
- Online,
- Connecting,
- }
- private Status serverStatus = Status.Offline;
- void OnGUI()
- {
- using (new GUILayout.HorizontalScope())
- {
- GUI.enabled = serverStatus != Status.Online;
- if (GUILayout.Button("Start Server"))
- {
- StartServer();
- }
- GUILayout.Label("Status: " + serverStatus.ToString());
- }
- GUI.enabled = true;
- using (new GUILayout.HorizontalScope())
- {
- if (GUILayout.Button("Start Client"))
- {
- StartClient();
- }
- GUILayout.Label(string.Format("{0} clients connected", clientIDs.Count));
- }
- }
- static ConnectionConfig CreateConnectionConfig()
- {
- ConnectionConfig conConfig = new ConnectionConfig();
- conConfig.NetworkDropThreshold = 20;
- conConfig.DisconnectTimeout = 5000;
- conConfig.AddChannel(QosType.ReliableSequenced);
- return conConfig;
- }
- private const int port = 1234;
- void StartServer()
- {
- NetworkTransport.Init();
- HostTopology topology = new HostTopology(CreateConnectionConfig(), 3000);
- serverHostID = NetworkTransport.AddHost(topology, port);
- serverStatus = Status.Online;
- InvokeRepeating("SendToClients", 0, 1);
- }
- void SendToClients()
- {
- byte error = 0;
- byte[] buffer = new byte[256];
- foreach (int clientID in clientIDs)
- {
- NetworkTransport.Send(serverHostID, clientID, 0, buffer, buffer.Length, out error);
- }
- }
- private int serverHostID;
- private List<int> clientIDs = new List<int>();
- void StartClient()
- {
- NetworkTransport.Init();
- byte error;
- int clientID = NetworkTransport.Connect(0, "127.0.0.1", port, 0, out error);
- Debug.LogFormat("Conn {0} err {1}", clientID, error);
- if (error == 0)
- {
- clientIDs.Add(clientID);
- }
- }
- void Update()
- {
- foreach (int clientID in clientIDs)
- UpdateClient(clientID);
- }
- void UpdateClient(int clientID)
- {
- int recHostId = serverHostID;
- int connectionId = clientID;
- int channelId = 0;
- 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.Nothing: //1
- break;
- case NetworkEventType.ConnectEvent: //2
- break;
- case NetworkEventType.DataEvent: //3
- break;
- case NetworkEventType.DisconnectEvent: //4
- break;
- }
- if (recData != NetworkEventType.Nothing)
- Debug.Log("Received " + recData);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement