Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by SteenPetersen · Aug 07, 2017 at 07:47 AM · networkwebglbrowser communication

WebGL and UNet. Cant seem to get in proper contact with server from browser.

Hi I am trying to setup a multiplayer game to be played through a browser using UNet. In the editor everything works fine, I followed a tutorial that said it should work in webgl but sadly it does not. There are two scripts as of yet one for the client and one for the server linked below. This is using mostly the LLAPI.

Wether I use the networkServer.usewebsocket = true or not the result is the same.

The debug og "finished connection" does show so it completes the OnConnection fuinction.

From the editor everything works fine but from the browser I get the following error:

"Attempt to send to not connected connection {1}" -- Since I get this error when ASKNAME is asked and when ASKPOSITION is asked I suspect that the SEND function is the problem im trying to send in a language the browser doesnt know but I dont know how to define this.

 private const int MAX_CONNECTION = 100;

 private int port = 3001;

 private List<ServerClient> clients = new List<ServerClient>();

 private float lastMovementUpdate;
 private float movementUpdateRate = 0.05f;

 private int socketId;
 private int webHostId;
 private int reliableChannel;
 private int unReliableChannel;

 private bool isStarted = false;
 private byte error;

 private void Start()
 {
     NetworkTransport.Init();
     ConnectionConfig cc = new ConnectionConfig();
     //NetworkServer.useWebSockets = true;

     reliableChannel = cc.AddChannel(QosType.Reliable);
     unReliableChannel = cc.AddChannel(QosType.Unreliable);

     HostTopology topo = new HostTopology(cc, MAX_CONNECTION);

     socketId = NetworkTransport.AddHost(topo, port, null);
     webHostId = 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.Nothing:         //1
             break;
         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 + "has sent : " + 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]));
                     break;

                 default:
                     Debug.Log("invalid message : " + msg);
                     break;
             }

             break;

         case NetworkEventType.DisconnectEvent: //4
             Debug.Log("Player " + connectionId + "has disconnected");
             OnDiconnection(connectionId);
             break;
     }

     if (clients.Count > 0)
     {
         if (Time.time - lastMovementUpdate > movementUpdateRate)
         {
             lastMovementUpdate = Time.time;
             string posMsg = "ASKPOSITION|";
             foreach (ServerClient sc in clients)

                 posMsg += sc.connectionId.ToString() + '%' + sc.position.x.ToString() + '%' + sc.position.y.ToString() + '|';
             posMsg = posMsg.Trim('|');

             Send(posMsg, unReliableChannel, clients);
         }
     }
 }


 private void OnConnection(int cnnId)
 {
     Debug.Log("Arrived at connection");
     ServerClient c = new ServerClient();
     c.connectionId = cnnId;
     c.playerName = "TEMP";
     clients.Add(c);

     string msg = "ASKNAME|" + cnnId + "|";
     foreach (ServerClient sc in clients)

         msg += sc.playerName + '%' + sc.connectionId + '|';

         msg = msg.Trim('|');

     Send(msg, reliableChannel, cnnId);

     Debug.Log("Finished at connection");
 }

 private void OnNameIS(int cnnId, string playerName)
 {
     // link the name to the connection ID
     clients.Find(x => x.connectionId == cnnId).playerName = playerName;

     // Tell evertone that a new player has connected
     Send("CNN|" + playerName + '|' + cnnId, reliableChannel, clients);
 }

 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(socketId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
     }
 }

 private void OnDiconnection(int cnnId)
 {
     clients.Remove(clients.Find(x => x.connectionId == cnnId));
     string msg = "DC|" + cnnId;
     Send(msg, reliableChannel, clients);
 }

 private void OnMyPosition(int cnnId, float x, float y)
 {
     clients.Find(clientInQuestion => clientInQuestion.connectionId == cnnId).position = new Vector3(x, y, 0);
 }


Here is the client Code:

     private const int MAX_CONNECTION = 100;
 
     private int port = 3001;
 
     private int hostId;
     private int webHostId;
     private int reliableChannel;
     private int unReliableChannel;
 
     private int connectionId;
     private int clientId;
 
 
     private bool isConnected = false;
 
     public bool isStarted = false;
 
     private float connectionTime;
 
     private string playerName;
 
     private byte error;
 
     public GameObject playerPrefab;
     public Dictionary<int, player> players = new Dictionary<int, player>();
 
     public void Connect()
     {
         Debug.Log("connecting...");
         // does player have a name?
         string pName = GameObject.Find("NameInput").GetComponent<InputField>().text;
         if (pName == "")
         {
             Debug.Log("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);
 
         connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);
 
         connectionTime = Time.time;
 
         isConnected = true;
 
         Debug.Log("connected");
     }
 
     private void Update()
     {
         connectionTime += Time.deltaTime;
 
         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 the client ID
         clientId = 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 OnAskPosition(string[] data)
     {
 
         if (!isStarted)
             return;
 
         //update everyone else
         for (int i = 1; i <= data.Length-1; i++)
         {
             string[] d = data[i].Split('%');
 
             //prevent the server from updating us
             if (clientId != int.Parse(d[0]))
             {
                 Debug.Log("updating position");
                 Vector3 position = Vector3.zero;
                 position.x = float.Parse(d[1]);
                 position.y = float.Parse(d[2]);
                 players[int.Parse(d[0])].avatar.transform.position = position;
             }
         }
 
         //send out own position
         Vector3 myPosition = players[clientId].avatar.transform.position;
         string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString();
         Send(m, unReliableChannel);
 
     }
 
     private void SpawnPlayer(string playerName, int cnnId)
     {
         GameObject go = Instantiate(playerPrefab) as GameObject;
 
         // is this ours?
 
         if(cnnId == clientId)
         {
             // add mobility
             go.AddComponent<PlayerController>();
 
             // remove Canvas
             GameObject.Find("Canvas").SetActive(false);
 
             isStarted = true;
         }
 
         player p = new player();
         p.avatar = go;
         p.playerName = playerName;
         p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
         p.connectionId = cnnId;
 
         players.Add(cnnId, p);
     }
 
     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);
         Debug.Log("player : " + players[cnnId].playerName + " has disconnected");
         players.Remove(cnnId);
     }
 
 }


I think this is a fairly common issue judging by my attempts to find an answer so any feedback would be appreciated, when I fix this issue I will post in great detail about it to make sure others can get this a bit clearer as well.

thank you.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SteenPetersen · Aug 07, 2017 at 06:18 PM 0
Share

Still haven't been able to figure this one out. Any help would be greatly appreciated.

avatar image SteenPetersen · Aug 08, 2017 at 05:57 AM 0
Share

Still no headway. Seems I have done everything that it says to do in (https://docs.unity3d.com/$$anonymous$$anual/UNetUsingTransport.html) about webgl.

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by SteenPetersen · Aug 08, 2017 at 03:04 PM

Solved this issue:

Was sending to hostId instead of websocketId so this:

     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);
         }
     }


was changed to this:

     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(webSocketId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
         }
     }

hope this helps someone.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

132 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

WebGL UnityWebRequest.Post in Firefox returning null from web service 0 Answers

JSLib - Get a reference to the player 0 Answers

WebGL & denying browser script access to game methods? 0 Answers

What's the proper way to make my game listen to a browser's javascript event? 0 Answers

Unity says my platformer micro game cannot be shared with webGL because the max size is 100 mb, but I should be able to share it 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges