Hey guys.
I am trying to make player with unity to watch video via network. Host some server and then send current frame of video to it. Other users would get a messages and compare to theirs frames.
For example: if user1 watch 54frame it will sends 54 frame. Other user will get 54frame then compare to their frame.
If (video.frame!=54) {video.frame=54}
But I cant connect correctly.
Here is my code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text;
using System;
using Byn.Net;
using System.Collections.Generic;
using Byn.Common;
using UnityEngine.Video;
/// <summary>
/// Contains a complete chat example.
/// It can run on Windows x86/x64 and in browsers. More platforms will be added soon.
///
/// The chat app will report during start which system it uses.
///
/// The user can enter a room name and click the "Open room" button to start a server and wait for
/// incoming connections or use the "Join room" button to join an already existing room.
///
///
///
///
/// As the system implements a server/client style connection all messages will first be sent to the
/// server and the server delivers it to each client. The server side ConnectionId is used to
/// identify a user.
///
///
/// </summary>
public class ChatApp : MonoBehaviour
{
/// <summary>
/// This is a test server. Don't use in production! The server code is in a zip file in WebRtcNetwork
/// </summary>
public string uSignalingUrl = "wss://because-why-not.com:12777/chatapp";
public string uIceServer = "stun:because-why-not.com:12779";
public string uIceServerUser = "";
public string uIceServerPassword = "";
/// <summary>
/// Mozilla stun server. Used to get trough the firewall and establish direct connections.
/// Replace this with your own production server as well.
/// </summary>
public string uIceServer2 = "stun:stun.l.google.com:19302";
/// <summary>
/// Set true to use send the WebRTC log + wrapper log output to the unity log.
/// </summary>
public bool uLog = false;
/// <summary>
/// Debug console to be able to see the unity log on every platform
/// </summary>
public bool uDebugConsole = false;
/// <summary>
/// The network interface.
/// This can be native webrtc or the browser webrtc version.
/// (Can also be the old or new unity network but this isn't part of this package)
/// </summary>
private IBasicNetwork mNetwork = null;
/// <summary>
/// True if the user opened an own room allowing incoming connections
/// </summary>
private bool mIsServer = false;
/// <summary>
/// Keeps track of all current connections
/// </summary>
private List<ConnectionId> mConnections = new List<ConnectionId>();
private const int MAX_CODE_LENGTH = 256;
/// <summary>
/// Will setup webrtc and create the network object
/// </summary>
///
//serverio pavadinimas:
string serveris = "serveris";
VideoPlayer video;
private void Start ()
{
//get video player
video = GetComponent<VideoPlayer>();
//WebRtcNetworkFactory factory = WebRtcNetworkFactory.Instance;
Setup();
mNetwork.StartServer(serveris);
// mNetwork.Connect(serveris);
}
private float period = 0.0f;
private void Update()
{
if (period > 0.2f)
{
//Do Stuff
SendString(video.frame.ToString());
period = 0;
}
period += Time.deltaTime;
}
private void OnLog(object msg, string[] tags)
{
StringBuilder builder = new StringBuilder();
TimeSpan time = DateTime.Now - DateTime.Today;
builder.Append(time);
builder.Append("[");
for (int i = 0; i< tags.Length; i++)
{
if(i != 0)
builder.Append(",");
builder.Append(tags[i]);
}
builder.Append("]");
builder.Append(msg);
Debug.Log(builder.ToString());
}
private void Setup()
{
Debug.Log("Initializing webrtc network");
mNetwork = WebRtcNetworkFactory.Instance.CreateDefault(uSignalingUrl, new IceServer[] { new IceServer(uIceServer, uIceServerUser, uIceServerPassword), new IceServer(uIceServer2) });
if (mNetwork != null)
{
Debug.Log("WebRTCNetwork created");
}
else
{
Debug.Log("Failed to access webrtc ");
}
}
private void Reset()
{
Debug.Log("Cleanup!");
mIsServer = false;
mConnections = new List<ConnectionId>();
Cleanup();
}
/// <summary>
/// called during reset and destroy
/// </summary>
private void Cleanup()
{
mNetwork.Dispose();
mNetwork = null;
}
private void OnDestroy()
{
if (mNetwork != null)
{
Cleanup();
}
}
private void FixedUpdate()
{
//check each fixed update if we have got new events
// HandleNetwork();
}
private void HandleNetwork()
{
//check if the network was created
if (mNetwork != null)
{
//first update it to read the data from the underlaying network system
mNetwork.Update();
//handle all new events that happened since the last update
NetworkEvent evt;
//check for new messages and keep checking if mNetwork is available. it might get destroyed
//due to an event
while (mNetwork != null && mNetwork.Dequeue(out evt))
{
//print to the console for debugging
Debug.Log(evt);
//check every message
switch (evt.Type)
{
case NetEventType.ServerInitialized:
{
//server initialized message received
//this is the reaction to StartServer -> switch GUI mode
mIsServer = true;
string address = evt.Info;
Debug.Log("Server started. Address: " + address);
// uRoomName.text = "" + address;
} break;
case NetEventType.ServerInitFailed:
{
//user tried to start the server but it failed
//maybe the user is offline or signaling server down?
mIsServer = false;
Debug.Log("Server start failed.");
Reset();
} break;
case NetEventType.ServerClosed:
{
//server shut down. reaction to "Shutdown" call or
//StopServer or the connection broke down
mIsServer = false;
Debug.Log("Server closed. No incoming connections possible until restart.");
} break;
case NetEventType.NewConnection:
{
mConnections.Add(evt.ConnectionId);
//either user runs a client and connected to a server or the
//user runs the server and a new client connected
Debug.Log("New local connection! ID: " + evt.ConnectionId);
//if server -> send announcement to everyone and use the local id as username
if(mIsServer)
{
//user runs a server. announce to everyone the new connection
//using the server side connection id as identification
string msg = "New user " + evt.ConnectionId + " joined the room.";
Debug.Log(msg);
SendString(msg);
}
} break;
case NetEventType.ConnectionFailed:
{
//Outgoing connection failed. Inform the user.
Debug.Log("Connection failed");
Reset();
} break;
case NetEventType.Disconnected:
{
mConnections.Remove(evt.ConnectionId);
//A connection was disconnected
//If this was the client then he was disconnected from the server
//if it was the server this just means that one of the clients left
Debug.Log("Local Connection ID " + evt.ConnectionId + " disconnected");
if (mIsServer == false)
{
Reset();
}
else
{
string userLeftMsg = "User " + evt.ConnectionId + " left the room.";
//show the server the message
Debug.Log(userLeftMsg);
//other users left? inform them
if (mConnections.Count > 0)
{
SendString(userLeftMsg);
}
}
} break;
case NetEventType.ReliableMessageReceived:
case NetEventType.UnreliableMessageReceived:
{
HandleIncommingMessage(ref evt);
} break;
}
}
//finish this update by flushing the messages out if the network wasn't destroyed during update
if(mNetwork != null)
mNetwork.Flush();
}
}
private void HandleIncommingMessage(ref NetworkEvent evt)
{
MessageDataBuffer buffer = (MessageDataBuffer)evt.MessageData;
string msg = Encoding.UTF8.GetString(buffer.Buffer, 0, buffer.ContentLength);
//if server -> forward the message to everyone else including the sender
if (mIsServer)
{
//we use the server side connection id to identify the client
string idAndMessage = evt.ConnectionId + ":" + msg;
SendString(idAndMessage);
Debug.Log(idAndMessage);
}
else
{
//client received a message from the server -> simply print
Debug.Log(msg);
}
//return the buffer so the network can reuse it
buffer.Dispose();
}
/// <summary>
/// Sends a string as UTF8 byte array to all connections
/// </summary>
/// <param name="msg">String containing the message to send</param>
/// <param name="reliable">false to use unreliable messages / true to use reliable messages</param>
private void SendString(string msg, bool reliable = true)
{
if (mNetwork == null)
{
Debug.Log("No connection. Can't send message. " + mConnections.Count);
}
else
{
byte[] msgData = Encoding.UTF8.GetBytes(msg);
foreach (ConnectionId id in mConnections)
{
mNetwork.SendData(id, msgData, 0, msgData.Length, reliable);
}
}
}
}
Maybe you have some better ideas or smthg?
Thanks a lot!