Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Collections;
- using System.Text;
- public class NetManager : MonoBehaviour {
- [SerializeField] private string ip = "127.0.0.1";
- public int unreliableChannelId;
- private int socketId;
- private int connectionId;
- private string message = "Default text";
- void Start()
- {
- // Initializing Network Transport Layer
- NetworkTransport.Init ();
- // Getting default configuration for host topology
- ConnectionConfig CConfig = new ConnectionConfig();
- unreliableChannelId = CConfig.AddChannel(QosType.Unreliable);
- // Creating host topology
- HostTopology topology = new HostTopology(CConfig, 2);
- // Open client socket
- socketId = NetworkTransport.AddHost (topology, 52000);
- Connect ();
- }
- void OnGUI ()
- {
- message = GUI.TextField(new Rect(10, 10, 200, 20), message, 25);
- if (GUI.Button(new Rect(20, 70, 120, 20), "Send message")) {
- SendSocketMessage(message);
- }
- }
- void Update()
- {
- int recHostId; // rec - received
- int recConnectionId;
- int recChannelId;
- byte[] recBuffer = new byte[1024];
- int bufferSize = 1024;
- int dataSize;
- byte error;
- NetworkEventType recNetworkEvent = NetworkTransport.Receive(out recHostId, out recConnectionId, out recChannelId, recBuffer, bufferSize, out dataSize, out error);
- switch (recNetworkEvent)
- {
- case NetworkEventType.Nothing:
- //Debug.Log("Nothing");
- break;
- case NetworkEventType.ConnectEvent:
- Connected (recConnectionId);
- break;
- case NetworkEventType.DataEvent:
- DataReceiver(recBuffer);
- //NetworkTransport.Disconnect(socketId, connectionId, out error);
- break;
- case NetworkEventType.DisconnectEvent:
- Debug.Log("Socket closed!");
- break;
- }
- }
- public void Connect()
- {
- byte error;
- connectionId = NetworkTransport.Connect(socketId, "127.0.0.1", 3000, 0, out error);
- Debug.Log("Connected to server. ConnectionId: " + connectionId);
- }
- public void SendSocketMessage(string msg) {
- byte error;
- byte[] buffer = new byte[1024];
- Encoding enc = Encoding.ASCII;
- int length = enc.GetByteCount(msg);
- buffer = enc.GetBytes (msg);
- int bufferSize = 1024;
- NetworkTransport.Send(socketId, connectionId, unreliableChannelId, buffer, length, out error);
- }
- private void Connected(int recConnectionId)
- {
- if( recConnectionId == connectionId ) {
- Debug.Log("Connection established!");
- }
- }
- private void DataReceiver(byte[] bytes)
- {
- byte error;
- Encoding enc = Encoding.ASCII;
- string message = enc.GetString(bytes);
- Debug.Log("Message received: " + message);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement