// Use this for initialization void Start() { if (GetComponent <NetworkIdentity>().isServer) { IniFile ini = new IniFile("Assets\\Scripts\\FahrradCom.EXE.ini"); string ip1 = ini.IniReadValue("TCP", "IP"); avr = new AVR_NetClient(ini.IniReadValue("TCP", "IP"), Int32.Parse(ini.IniReadValue("TCP", "Port")), Int32.Parse(ini.IniReadValue("TCP", "BufferSize"))); Debug.Log("avr" + avr); speed = new Speed(Int32.Parse(ini.IniReadValue("Speed", "SensorCount")), Int32.Parse(ini.IniReadValue("Speed", "SpeedSample")), Double.Parse(ini.IniReadValue("Speed", "WheelLine"))); //Debug.Log (ini.IniReadValue ("Speed", "SensorCount") + ini.IniReadValue ("Speed", "SpeedSample") + ini.IniReadValue ("Speed", "WheelLine")); // Winkel Angle angle = new Angle(Int32.Parse(ini.IniReadValue("Angle", "SensorMinValue")), Int32.Parse(ini.IniReadValue("Angle", "SensorMaxValue")), Int32.Parse(ini.IniReadValue("Angle", "SensorRange")), ini.IniReadValue("Angle", "SwitchDirection") == "0" ? true : false); // Daten zum lesen via TCP - die werden immer abgefragt NetData rd = new NetData(); // Zum Beispiel: rd.addData(CONST.getANGLE()); //Winkel rd.addData(CONST.getSPEED()); //Geschwindigkeit // rd.addData(CONST.getSTATE()); //Status // Zuordnung der Datensets für die Kommunikation mit AVR avr.setDataToRead(rd); /* Ein Thread für die Kommunikation. * Ist wichtig vor allem für die Geschwindigkeitsberechnung. * Der SpeedSensor liefert eigentlich nur FALSE, wenn die MetallStücke am Rad (9 Stück) * vorbei "fahren" und TRUE wenn "die Luft rein ist". Die Abstände sind gleich (?), * deswegen auf Grund bekantes Radumfangs, auch die Teilstrecken (zwischen 2 Metallstücken) * einfach zu berechnen. * Für die Geschwindigkeit fehlt nun nur die Zeit. Die bekommt man, in dem man die Zeituterschiede * in Millisekunden zwischen 2 SpeedSensor-Aktivierungen ablesen kann. Je genauer desto besser. */ tavr = new Thread(avr.startThread); tavr.Start(); // Thread zum Lesen von Daten von AVR trd = new Test_ReadData(speed, angle, rd, Int32.Parse(ini.IniReadValue("Speed", "SpeedResetAfter"))); ttrd = new Thread(trd.StartThread); ttrd.Start(); } }
private int fGrenze = 500; //Speedsensor liefert eigentlich nur ca. 0V oder 5V //ist aber zur ADC angeschlossen. Von ADC bekommen wird //entsprechend etwas um 9 und 1023. public Test_ReadData(Speed aSpeed, Angle aAngle, NetData aReadNetData, int aSpeedResetTime) { speed = aSpeed; angle = aAngle; rnd = aReadNetData; this.fSpeedResetTime = aSpeedResetTime * 1000; }
public void Push(NetData tcpChannel) { lock (_pool) { _pool.Enqueue(tcpChannel); } }
public void SendBroadcast(InternalData message) { foreach (ClientInfo clientInfo in clientList) { doSend(NetData.PackageData(getNextMessageID(), message.ToByteArray()), clientInfo); } }
public void Recieve(byte[] bytes) { NetData message = NetData.RecoverBytes(bytes); if (message != null && message.number > lastMessageNumber) { if (ServerHandler.clients.Contains(message.sender.ID)) { if ((ServerHandler.clients[message.sender.ID] as NetUser).udpConnection == null) { NetUser.OnUserConnectedUDP(message.sender); } netUser = ServerHandler.clients[message.sender.ID] as NetUser; netUser.udpConnection = this; } else { netUser = new NetUser(message.sender); netUser.udpConnection = this; ServerHandler.AddConnection(netUser); NetUser.OnUserConnectedUDP(message.sender); } NetUser.OnUdpMessageHandleCallback(bytes, message, netUser); lastMessageNumber = message.number; } }
public void SendMessageUDP(NetData message) { message.SetNumber(numberUDP); byte[] data = NetData.GetBytesData(message); udpClient.Send(data, data.Length); numberUDP++; }
/// <summary> /// subject 콜백 /// </summary> private void connectServer(NetData netData) { m_bConnecting.Value = true; var stream = ObservableWWW.PostWWW(URLData.BaseServer, netData.data.form()).CatchIgnore((WWWErrorException ex) => { Debug.LogError(ex.RawErrorMessage); if (ex.HasResponse) { Debug.LogError(ex.StatusCode); } foreach (var item in ex.ResponseHeaders) { Debug.LogError(item.Key + ":" + item.Value); } netData.Destroy(); }); stream.Subscribe(_ => { m_bConnecting.Value = false; object dic_reciveObject = Json.Deserialize(_.text); Dictionary <string, object> data = (Dictionary <string, object>)dic_reciveObject; netData.subject.OnNext(data); netData.subject.OnCompleted(); }).Dispose(); }
internal ScoreboardNetInfo(NetData data) { Name = data.Name; Ip = data.Ip; NetMask = data.NetMask; DefaultGateway = data.DefaultGateway; }
private void ConnectContinue() { try { udpClient.Connect(remoteAddressUDP); Thread.Sleep(100); stream = tcpClient.GetStream(); byte[] data = new NetData(new Containers.IntContainer(0x1B39), user.ID, false).bytes; stream.Write(data, 0, data.Length); Thread.Sleep(100); udpClient.Send(data, data.Length); onConnectCondition = true; ReceiveMessageTCP(); ReceiveMessageUDP(); } catch (Exception e) { OnLogReceived(e.Message); } }
/// <summary> /// Sends a message to the server /// </summary> /// <param name="data">Ithe InternalData object that contains the complete message</param> public void Send(InternalData data) { List <byte[]> msgData = NetData.PackageData(getNextID, data.ToByteArray()); //Send message to server if (msgData != null) { foreach (byte[] b in msgData) { if (b.Length != 1024) { LogEvent("Error: Attempting to send a message of incorrect size"); } else { try { //Send it to the server clientSocket.BeginSend(b, 0, b.Length, SocketFlags.None, new AsyncCallback(onSend), null); } catch (Exception ex) { LogEvent("Error: Failed to send message.\r\n" + ex); Disconnect("Failed to send message. See log for details."); break; //This message is messed up anyway } } } } else { LogEvent("Error: Attempting to send a null message"); } }
/// <summary> /// 消息分发 /// </summary> /// <param name="data"></param> private void Notify(Connection connect, NetData data) { if (m_EventDic.ContainsKey(data.dataType)) { m_EventDic[data.dataType].Invoke(data); } }
/// <inheritdoc/> public override void Read(NetPacketReader message) { base.Read(message); try { NetworkID = message.GetUInt(); MethodID = message.GetUShort(); RPCInfo = Network.InstanceType == NetInstanceType.Server ? (RPCInfo)Network.ServerRPCLookupTable.GetRPCInfo(MethodID) : Network.ClientRPCLookupTable.GetRPCInfo(MethodID); ParametersNum = RPCInfo.ParameterTypes.Length; if (Parameters.Length < ParametersNum) { Parameters = new object[ParametersNum]; } for (int i = 0; i < ParametersNum; i++) { Parameters[i] = NetData.Read(RPCInfo.ParameterTypes[i], message); } } catch (Exception e) { throw new MalformedPacketException("Failed to read packet.", e); } }
private void ConnectCallback(IAsyncResult asyncConnect) { if (!client.Connected) { Debug.LogError("connectFail--"); return; } Debug.Log("connectSuccess"); outStream = client.GetStream(); outStream.BeginRead(byteBuffer, 0, MAX_READ, readAsync, null); //断线重连发送数据 while (m_sendqueue.Count > 0) { NetData data = m_sendqueue.Dequeue(); if (!Send(data.m_serverRequest, data.m_correlationid, data.m_data, data.m_data.Length)) { break; } } //NetworkManager.AddEvent(Protocal.Connect, new ByteBuffer()); //Message connected = GIMessageFactory.GetMessage(EUIMessage.UI_NETWORK_CONNECTED, null); //MessageManager.DispatchMessage(connected); }
public override void OnPhysicsCheckStay(NetData other) { if (other.tag == "Player" && other != user) { UnityEngine.Debug.Log("Stay触发 " + other.name); } }
//Activates when start game is cliekd public void requestStart() { Multiplayer m = FindObjectOfType <Multiplayer>(); NetData n = new NetData("request_start", ""); m.sendData(JsonConvert.SerializeObject(n)); }
private void AddToSendQueue(int correlationid, NetProtocal.Request cmdtype, byte[] data, int len) { Debug.Log("###########################\nsend data error AddToSendQueue"); NetData sendata = new NetData(correlationid, cmdtype, data, len); m_sendqueue.Enqueue(sendata); }
// 主线程 public void Update() { if (!mDebugLog.IsNullOrEmpty()) { Debug.Log(mDebugLog); mDebugLog = null; } int len = msgList.Count; for (int i = len - 1; i >= 0; i--) { msgList[i].mfun(msgList[i].data); msgList.RemoveAt(i); } lock (_obj) { if (_isdirty) { _isdirty = false; if (Waitflag == false) { //// if (NetWorkLoadingHandler.Instance.isShow() == true) // NetWorkLoadingHandler.Instance.PopLoading(); } else { //NetWorkLoadingHandler.Instance.PushLoading(); } } m_servertime += Time.deltaTime; while (m_revqueue.Count > 0) { NetData data = m_revqueue.Dequeue(); ClearStream(m_protoms); m_protoms.Write(data.m_data, 0, data.m_data.Length); m_protoms.Seek(0, SeekOrigin.Begin); if (Define.UpdateMode) { PraseData(data); } else { try { PraseData(data); // NetDataMgr.instance.DispatchData(data.m_serverno, obj); // 把数据发送到数据管理类中进行处理 这样好处是 不跟框架扯什么关系 // MessageManager.DispatchMessage(GIMessageFactory.GetMessage((ServiceNo)(data.m_serverno), obj));//把协议分发到客户端内部消息队列 } catch (Exception) { Debug.LogError(data.m_serverRequest.ToString() + ";len:" + data.m_data.Length); throw; } } } } }
public Packet(byte[] data) { dataObjs = new List<NetData>(); packet_type = (PacketType)data[0]; int iterator = 1; while (iterator < data.Length) { //NetDataType d = (NetDataType)data[iterator]; int dLen = (int)data[iterator + 1]; byte[] nObjData = new byte[dLen + 2]; //from iterator to dLen+2 for (int i = iterator; i < iterator + dLen + 2; i++) { nObjData[i - (iterator)] = data[i]; } NetData nObj = new NetData(nObjData); dataObjs.Add(nObj); iterator += dLen + 2; } }
/// <summary> /// 获取网络的传输速率 /// </summary> /// <param name="nd">上传或下载</param> /// <returns></returns> public static double GetNetData(NetData nd) { if (InstanceNames.Length == 0) { return(0); } double d = 0; for (int i = 0; i < InstanceNames.Length; i++) { double receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]); double send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]); switch (nd) { case NetData.Received: d += receied; break; case NetData.Sent: d += send; break; case NetData.ReceivedAndSent: d += receied + send; break; default: d += 0; break; } } return(d); }
public new void Update() { while (m_ReceiveQueue.Count > 0) { ReceiveObject receiveObject = null; //从处理队列中得到需要处理的协议对象 if (m_ReceiveQueue.TryDequeue(out receiveObject)) { ServerMessageReceiveDelegate messageReceiveDelegate = null; if (m_ReceiveDelegateDic.TryGetValue(receiveObject.command, out messageReceiveDelegate)) { NetData netData = receiveObject as NetData; //业务处理 messageReceiveDelegate(netData.clientId, netData.message); } continue; } } for (int index = 0; index < m_ClientList.Count; index++) { m_ClientList[index].Update(); } BeginAccept(); }
/// <summary> /// 恢复数据 /// </summary> void ResetData() { // 恢复对数据的应用 netDataReceive = null; netDataSend = null; if (chessCluster != null) { foreach (Chess item in chessCluster) { Destroy(item.gameObject); } } chessCluster = new List <Chess>();; selfChessCluster = new List <Chess>(); otherChessCluster = new List <Chess>(); selfStage = GameStage.None; otherStage = GameStage.None; FirstChess = null; if (SelectedIGrid != null) { SelectedIGrid.HideSelectedTag(); SelectedIGrid = null; } if (GoneIGrid != null) { GoneIGrid.HideGoneTag(); GoneIGrid = null; } }
public override void Action(CommandCaller caller, string input, string[] args) { if (NetData.IsPlayerServerOwner(PlayerData.MyPlayer)) { if (args.Length > 0) { string name = string.Join(" ", args); if (name.Length <= 20) { DUtils.Chat($"Changed {Main.worldName}'s name to '{name}'!", true, Color.CornflowerBlue.R, Color.CornflowerBlue.G, Color.CornflowerBlue.B); Main.worldName = name; } if (name.Length > 20) { Main.NewText("ERROR: You cannot have a name longer than 20 characters."); } } else { Main.NewText("ERROR: You have not specified a name."); } } else { Main.NewText("ERROR: You are not the server host."); } }
public void InitUdpListener(bool bInIsServer) { if (Client == null) { bIsServer = bInIsServer; if (bIsServer) { Client = new UdpClient(ServerPort); ReceiveEndPoint = new IPEndPoint(IPAddress.Any, ServerPort); } else { bool bKeepConnecting = true; while (bKeepConnecting) { try { Client = new UdpClient(ClientPort); ReceiveEndPoint = new IPEndPoint(IPAddress.Any, ClientPort); bKeepConnecting = false; } catch { ++ClientPort; } } } StateData = new NetData(); StateData.e = ReceiveEndPoint; StateData.u = Client; } }
public void ReceiveMessageUDPCallback(IAsyncResult ar) { ReceiveMessageUDP(); try { byte[] data = udpClient.EndReceive(ar, ref remoteAddressUDP); onMessageRecieveUDP(NetData.RecoverBytes(data)); } catch { if (stream != null) { stream.Flush(); stream.Dispose(); stream = null; } if (tcpClient != null) { tcpClient.Client.Close(); tcpClient.Dispose(); tcpClient = null; } if (udpClient != null) { udpClient.Dispose(); udpClient = null; } onConnectionLost?.Invoke(); } }
private void ReceiveCallback(IAsyncResult ar) { try { NetData state = (NetData)ar.AsyncState; Socket client = state.workSocket; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { using (Stream ms = new MemoryStream()) { ms.Position = 0; ms.Write(state.buffer, 0, bytesRead); ms.Position = 0; if (OnReceived != null) { OnReceived(ms); } } } } catch (Exception e) { } }
public void hostGuessResponse(NetData packet) { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif }
public override void PickUp(NetData other) { // (other as PlayerData).skillList.AddSkill(SkillManager.GetSkill(skillId)); var player = (other as PlayerData); player.weaponSystem.AddWeapon(weaponId); base.PickUp(other); }
public void Init(float firingRate, NetData User) { this.firingInterval = new Fixed(1 / firingRate); lastTime = Fixed.Zero; // gunSetting = DataManager.Instance.gunManager.gun; this.user = User; timer = Fixed.Zero; }
public void SendMessageTCP(NetData message) { message.SetNumber(numberTCP); byte[] data = NetData.GetBytesData(message); stream.Write(data, 0, data.Length); stream.Flush(); numberTCP++; }
public void JoinGame(string playerName, int code) { NetData n = new NetData("join_lobby", playerName); n.id = code; nameUsed = playerName; sendData(JsonConvert.SerializeObject(n)); }
/// <summary> /// 棋子下棋行为,网络发送 /// </summary> /// <param name="Action">类型,Move / Eat</param> /// <param name="fromX"></param> /// <param name="fromY"></param> /// <param name="toX"></param> /// <param name="toY"></param> public void ChessActionBehavior(string Action, float fromX, float fromY, float toX, float toY) { netDataSend = new NetData("Doing"); netDataSend.netChessActions = new NetChessAction(Action, (int)fromX, (int)fromY, (int)toX, (int)toY); string tmp = JsonMapper.ToJson(netDataSend); SendNetMessage(tmp); }
public override void OnPhysicsCheckExit(NetData other) { if (other.tag == "Player" && other != user) { UnityEngine.Debug.Log("Exit触发Bullet!!!!"); //Destory<Bullet>(this.show); } }
public void Create(int bufferLength, int poolSize) { if (bufferLength > 0) BufferSize = bufferLength; if (poolSize > 0) BufferPoolSize = poolSize; _pool = new Queue<NetData>(); for (int i = 0; i < poolSize; i++) { NetData tcpChannel = new NetData(); tcpChannel.Pool = this; _pool.Enqueue(tcpChannel); } }
public NetData Pop() { NetData tcpChannel = null; lock (_pool) { if (_pool.Count > 0) tcpChannel = _pool.Dequeue(); } if (tcpChannel == null) { tcpChannel = new NetData(); tcpChannel.Pool = this; } return tcpChannel; }
public void Push_nData(NetData data) { dataObjs.Add(data); }
public int sceUtilityGetNetParam(int conf, int param, NetData* data) { PointerUtils.StoreStringOnPtr("Temp", Encoding.UTF8, data[0].asString, 128); //throw(new NotImplementedException()); return 0; }
public double GetNetData(NetData nd) { NetDateRead(); if (_instanceNames.Length == 0) return 0; double d = 0; for (int i = 0; i < _instanceNames.Length; i++) { d += nd == NetData.Received ? GetCounterValue(_netRecvCounters[i], "Network Interface", "Bytes Received/sec", _instanceNames[i]) : nd == NetData.Sent ? GetCounterValue(_netSentCounters[i], "Network Interface", "Bytes Sent/sec", _instanceNames[i]) : nd == NetData.ReceivedAndSent ? GetCounterValue(_netRecvCounters[i], "Network Interface", "Bytes Received/sec", _instanceNames[i]) + GetCounterValue(_netSentCounters[i], "Network Interface", "Bytes Sent/sec", _instanceNames[i]) : 0; } return d; }
private void Awake() { instance = this; GetVKID(); GetSchoolId(); }