public int Connect(string ip, int port, RecvData recvFun, SvrBreak svbkFun) { if (this.state != 0) { return(100 + this.state); } if (this.socket == null) { this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } IPAddress address = IPAddress.Parse(ip); EndPoint remoteEP = new IPEndPoint(address, port); try { this.socket.Connect(remoteEP); } catch (Exception) { return(1); } this.state = 2; this.recvFun = recvFun; this.svbkFun = svbkFun; new Thread(new ThreadStart(this.Receive)) { Priority = ThreadPriority.BelowNormal }.Start(); return(0); }
/// <summary> /// 数据处理 /// </summary> /// <param name="o">socket对象</param> /// <param name="a1">字节数据</param> /// <param name="length">长度</param> private void DataHandle(Socket o, byte[] a1, int length) { try { //string s=ConvertHelper.BytesToString(a1, Encoding.UTF8).Replace("\0",""); //a1 = ConvertHelper.StringToBytes(s, Encoding.UTF8); //object objs = new StruFS1016AlarmInfo(); // ConvertHelper.ByteArrayToStructureEndian(a1, ref objs, 0);//ConvertHelper.BytesToStruct<StruFS1016AlarmInfo>(a1); //ConvertHelper.BytesToStruct(a1, typeof(StruFS1016AlarmInfo)); StruFS1016AlarmInfo obj = ConvertHelper.BytesToStruct <StruFS1016AlarmInfo>(a1);//(StruFS1016AlarmInfo)objs; StruNetHeartBeatInfo heart = new StruNetHeartBeatInfo(); if (obj.ccHeader.sync_code != null) { if (obj.ccHeader.header_type == 1) { return; } RecvData?.Invoke(obj, ((IPEndPoint)o.RemoteEndPoint).Address.ToString()); } else { heart = ConvertHelper.BytesToStruct <StruNetHeartBeatInfo>(a1);//ConvertHelper.BytesToStruct(a1, typeof(StruNetHeartBeatInfo)); } } catch (Exception) { } }
/// <summary> /// /// </summary> public RecvData execSerial(int func, int addr, int value) { int data = 0; RecvData recvData = new RecvData(); byte[] srcBuff = createPacket(func, addr, value).ToArray(); byte[] dstBuff = new byte[defComMaxDataSize]; //// comSerial.Send(srcBuff); Thread.Sleep(3000); int len = comSerial.Read(dstBuff); //// msgRecvData(dstBuff, len); //// if (!parsePacket(dstBuff, len)) { recvData.data = -1; return(recvData); } //// recvData.data = (Func.asc2int((int)dstBuff[3]) << 4) + Func.asc2int((int)dstBuff[4]); recvData.status = (Func.asc2int((int)dstBuff[5]) << 4) + Func.asc2int((int)dstBuff[6]); return(recvData); }
public override void Initialize() { initData = (GameSection.GetEventData() as InitData); this.recvData = new RecvData[initData.digit.Length]; for (int i = 0; i < this.recvData.Length; i++) { this.recvData[i] = new RecvData(); RecvData recvData = this.recvData[i]; recvData.digit = initData.digit[i]; recvData.selectValue = 0; recvData.ancer = 0; } base.Initialize(); }
private async Task HandleDataPostAsync(HttpListenerRequest req, HttpListenerResponse resp) { string reqcontent = await GetStringContentAsync(req); JObject json = JObject.Parse(reqcontent); recvData = json.ToObject <RecvData>(); recvX = recvData.recvX; recvY = recvData.recvY; recvOrientation = (int)recvData.recvOrientation; await BuildResponse(resp, req.ContentEncoding, json.ToString()); }
public void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort _SerialPort = (SerialPort)sender; string recvData = _SerialPort.ReadExisting(); if (HexRecv) { foreach (char tmp in recvData.ToCharArray()) { RecvData.Append(string.Format("{0:X2} ", Convert.ToInt32(tmp))); } } else { RecvData.Append(recvData); } if (SaveRecv) { RecvAutoSave = "保存中"; SaveRecvData(recvData); } else { RecvAutoSave = "已停止"; } RecvDataCount += recvData.Length; RecvHeader = "接收区:已接收" + RecvDataCount + "字节,接收自动保存[" + RecvAutoSave + "]"; if (RecvDataCount > (32768 * RecvDataDeleteCount)) { RecvData.Delete(); /* 32MB */ RecvDataDeleteCount += 1; } }
public int Listen(int port, int len, CliConn clcnFun, CliBreak clbkFun, RecvData recvFun) { if (this.state != 0) { return(100 + this.state); } if (this.socket == null) { this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.connClient = new ClientThread[100]; this.stack = new int[100]; this.length = 100; this.number = 0; this.top = 0; for (int i = 0; i < 100; i++) { this.connClient[i] = null; } } try { EndPoint localEP = new IPEndPoint(0L, port); this.socket.Bind(localEP); this.socket.Listen(len); } catch (Exception) { return(1); } this.clcnFun = clcnFun; this.clbkFun = clbkFun; this.recvFun = recvFun; this.state = 1; new Thread(new ThreadStart(this.Listening)) { Priority = ThreadPriority.BelowNormal }.Start(); return(0); }
public void comFunction2(int func) { int addr = 1; addr |= (userControl2.checkOWBit.Checked) ? 0x04 : 0x00; //// COMポートの接続確認 if (!bComOpen) { return; } //// Zappingの場合の実行確認 if (!msgZapping(func)) { return; } //// ログ表示 msgFunction(func, addr); //// シリアル通信 RecvData recvdata = execSerial(func, addr, (int)userControl2.numericWrite.Value); //// if (recvdata.data < 0) { StatusWriteLine("通信エラー"); return; } //// ステータス表示 userControl2.labelOTP.Text = msgStatus(recvdata.status); //// 画面表示 userControl2.textBoxRead.Text = recvdata.data.ToString(); }
//TODO assign the communication class here public CommunicationInterface() { DrivingInterface = new DrivingInterfaceVM(); MiniMap = new MiniMapVM(); SteeringWheel = new SteeringWheelVM(); recvX = 0; recvY = 0; recvOrientation = 0; timer = new System.Timers.Timer(Constants.SYSTEM_TICK_MS); timer.Elapsed += Timer_Elapsed; //Comm. parameters recvData = new RecvData(); //Data to Get (answer to POST) sendData = new SendData(); //Data to Send (answer to GET) listener = new HttpListener(); listener.Prefixes.Add(URI); listener.Start(); lThread = new Thread(new ThreadStart(listenThread)); lThread.Start(); }
/// <summary> /// 数据处理 /// </summary> /// <param name="o">socket对象</param> /// <param name="a1">字节数据</param> /// <param name="length">长度</param> private void DataHandle(Socket o, byte[] a1, int length) { try { string data = Encoding.UTF8.GetString(a1, 0, length); if (data.Contains("zzzdgykzjksjend\r\n") && data.Contains("zzzdgykzjksjstart")) { data = data.Replace("zzzdgykzjksjend\r\n", "").Replace("zzzdgykzjksjstart", ""); data = data.Substring(21); int x = data.Length / 27; int state = 0; for (int i = 0; i < x; i++) { string str = data.Substring(i * 27, 27); string boxId = str.Substring(1, 2); if (int.Parse(boxId) == 0) { break; } ZDPowerData newZDPowerData = new ZDPowerData() { Id = str.Substring(0, 1), AlarmStatus = str.Substring(3, 2), BoxId = boxId, AfterPowerFlow = double.Parse(str.Substring(21, 4).Insert(3, ".")).ToString(), AfterVoltage = double.Parse(str.Substring(15, 6)).ToString(), BeforePowerFlow = double.Parse(str.Substring(11, 4).Insert(3, ".")).ToString(), BeforeVoltage = double.Parse(str.Substring(5, 6)).ToString(), ConnectionStatus = str.Substring(25, 1), Position = ((IPEndPoint)o.RemoteEndPoint).Address.ToString(), EventTime = DateTime.Now }; if (i > 0) { newZDPowerData.ConnectionStatus = state.ToString(); } if (newZDPowerData.ConnectionStatus == "1" || newZDPowerData.AlarmStatus == "01" || newZDPowerData.AlarmStatus == "15") { state = 1; newZDPowerData.AfterPowerFlow = newZDPowerData.AfterVoltage = newZDPowerData.BeforePowerFlow = newZDPowerData.BeforeVoltage = "0"; } int oldDataFirst = oldData.FindIndex(v => v.BoxId == newZDPowerData.BoxId && v.Position == newZDPowerData.Position); if (oldDataFirst >= 0) { if (newZDPowerData.AlarmStatus != "00" || newZDPowerData.ConnectionStatus != "0") { if (oldData[oldDataFirst].AlarmStatus == newZDPowerData.AlarmStatus && oldData[oldDataFirst].ConnectionStatus == newZDPowerData.ConnectionStatus) { continue; } else { oldData[oldDataFirst] = newZDPowerData; } } else { oldData[oldDataFirst] = newZDPowerData; } } else { oldData.Add(newZDPowerData); } RecvData?.Invoke(newZDPowerData, ((IPEndPoint)o.RemoteEndPoint).Address.ToString()); } } } catch (Exception) { } finally { SendData(((IPEndPoint)o.RemoteEndPoint).Address.ToString(), ((IPEndPoint)o.RemoteEndPoint).Port, "zzzdgyjk000210Zzzzdgyjk" + Environment.NewLine); } }
private static void ReceiveCallBack(IAsyncResult ar) //서버에게 신호를 받았을 때 { RecvData recvData = (RecvData)ar.AsyncState; //리시브된 데이터 int receive = recvData.socket.EndReceive(ar); //리시브된 정보가 있는지 체크 if (receive <= 0) //서버 종료 { recvData.socket.Close(); //소켓을 닫음 Application.Quit(); return; } IntPtr buff = Marshal.AllocHGlobal(recvData.buffer.Length); //받은 byte 데이터를 struct로 변환 Marshal.Copy(recvData.buffer, 0, buff, recvData.buffer.Length); Type type = typeof(sGameRoom); room = (sGameRoom)Marshal.PtrToStructure(buff, type); if (room.flag == (int)eMSG.em_LOGIN) { Type m_type = typeof(sLogin); sLogin loginInfo = (sLogin)Marshal.PtrToStructure(buff, m_type); userScript.LoginResult(loginInfo.nick, loginInfo.loginSucc); } else if (room.flag == (int)eMSG.em_LOGINCHECK) { Type m_type = typeof(sLoginCheck); sLoginCheck loginChk = (sLoginCheck)Marshal.PtrToStructure(buff, m_type); fScript.FriendAccCheck(loginChk.nick, loginChk.loginChk); } else if (room.flag == (int)eMSG.em_MATCHREQUEST) { Type m_type = typeof(sMatchReq); sMatchReq matchReq = (sMatchReq)Marshal.PtrToStructure(buff, m_type); fScript.MatchReqResult(matchReq.sendUserNick, matchReq.matchSucc); } else if (room.flag == (int)eMSG.em_ENTER) //매칭 버튼을 눌렀다는 정보 { if (room.userNum == 0) //상대가 없음 { gScript.Matching(); } else //상대가 접속 { enterNum = room.userNum; gScript.MatchSucc(); } } else if (room.flag == (int)eMSG.em_CHARINFO) //아이템 선택이 끝났다는 정보 { Type m_type = typeof(sCharInfo); sCharInfo charInfo = (sCharInfo)Marshal.PtrToStructure(buff, m_type); if (enterNum == 1) //내가 먼저 입장 { sScript.SpawnInfo("Spawn1", "Spawn2", charInfo); } else if (enterNum == 2) //상대가 먼저 입장 { sScript.SpawnInfo("Spawn2", "Spawn1", charInfo); } } else if (room.flag == (int)eMSG.em_READY) //두 유저 모두 준비되었다는 정보 { sScript.SpawnReady(); } else if (eScript != null && room.flag == (int)eMSG.em_MOVE) //적의 좌표, 회전 정보 { Type m_type = typeof(sMove); sMove move = (sMove)Marshal.PtrToStructure(buff, m_type); Vector3 enemyPos = new Vector3(move.x, move.y, move.z); Quaternion enemyRot = new Quaternion(move.rotX, move.rotY, move.rotZ, move.rotW); eScript.EnemyMove(enemyPos, enemyRot); } else if (room.flag == (int)eMSG.em_ATK) //적이 공격했다는 정보 { Type m_type = typeof(sAtk); sAtk atk = (sAtk)Marshal.PtrToStructure(buff, m_type); eScript.EnemyAtk(atk.atkAni); } else if (room.flag == (int)eMSG.em_HIT) //내가 공격을 성공함 { Type m_type = typeof(sHit); sHit hit = (sHit)Marshal.PtrToStructure(buff, m_type); pScript.ChangePlayerHp(hit.hp); pScript.PlayerDamage(hit); } else if (room.flag == (int)eMSG.em_INFO) //적의 hp정보가 변한경우 { Type m_type = typeof(sChangeInfo); sChangeInfo hpInfo = (sChangeInfo)Marshal.PtrToStructure(buff, m_type); eScript.ChangeEnemyHp(hpInfo.hp); } else if (room.flag == (int)eMSG.em_ITEMSPAWN) { Type m_type = typeof(sItemSpawn); sItemSpawn itemSpawn = (sItemSpawn)Marshal.PtrToStructure(buff, m_type); pScript.passOnItemSpawnInfo(itemSpawn.itemKind); pScript.GetAtkMgrFromServer(true); } else if (room.flag == (int)eMSG.em_USEITEM) //아이템 사용 { Type m_type = typeof(sUseItem); sUseItem useItem = (sUseItem)Marshal.PtrToStructure(buff, m_type); pScript.ChangeItemImg(useItem.itemNum, true); pScript.ChangePlayerHp(useItem.hp); pScript.ChangePlayerSpeed(useItem.speed); } else if (room.flag == (int)eMSG.em_ENDITEM) //아이템 시간 끝 { Type m_type = typeof(sEndItem); sEndItem endItem = (sEndItem)Marshal.PtrToStructure(buff, m_type); pScript.ChangeItemImg(endItem.itemNum, false); pScript.ChangePlayerSpeed(endItem.speed); } else if (room.flag == (int)eMSG.em_GETOBJ) //던질 물건 잡기 { Type m_type = typeof(sGetObj); sGetObj getObj = (sGetObj)Marshal.PtrToStructure(buff, m_type); Debug.Log("from server get succ"); eScript.GetThrowObj(getObj.itemNum); } else if (room.flag == (int)eMSG.em_THROWOBJ) //물건 던지기 { eScript.ThrowObj(); Debug.Log("from server throw succ"); } else if (room.flag == (int)eMSG.em_END) //게임이 종료되었을 경우 { Type m_type = typeof(sEnd); sEnd esc = (sEnd)Marshal.PtrToStructure(buff, m_type); gameResult = esc.result; enemyNick = esc.enemyNick; if (pScript == null) { sScript.GameEndTrue(); } else { pScript.GameEndTrue(); } } else if (room.flag == (int)eMSG.em_CHAT) //채팅 { Type m_type = typeof(sChat); sChat chat = (sChat)Marshal.PtrToStructure(buff, m_type); string nowChat = new string(chat.chat); chatScript.ChatRecv(nowChat); } }
internal void OnRecvData(ClientSession session, byte[] data, int offset, int size) { RecvData?.Invoke(session, data, offset, size); }
/// <summary> /// JS消息传回 (注意:JS的消息0~10为内部消息,请使用以外的消息值) /// </summary> /// <param name="p_Msg"></param> /// <returns></returns> virtual protected string JsRecvData(IntPtr hWnd, int msg, int param_int, string param_str, string data) { try { if (hWnd != this.Handle) { return(""); } //页面载入完成 if (msg == 1) { string s_Js = @""; s_Js += "function Cef(nMsg, nParam, sParam, sData) { "; s_Js += "var o_cefobj = new cef.cefmsg.msg_object; "; s_Js += "var vParam = sParam == 'undefined'?' ':sParam; "; s_Js += "var vData = sData == 'undefined'?' ':sData; "; s_Js += "return o_cefobj.SendMessage(" + this.Handle.ToString() + ", nMsg, nParam, vParam, vData); "; s_Js += "} "; Js(s_Js); if (LoadEnd != null) { LoadEnd.Invoke(this); } return(""); } //事件回调 if (msg == 2 && param_int == 1) { if (param_str.Trim() != "undefined") { if (m_dicJsEventEvents.ContainsKey(param_str)) { if (m_dicJsEventEvents[param_str] != null) { return(m_dicJsEventEvents[param_str].Invoke(data)); } } } return(""); } //JSON回调 if (msg == 2 && param_int == 2) { if (param_str.Trim() != "undefined" && data.Trim() != "undefined") { if (m_dicJsonEvents.ContainsKey(param_str)) { if (m_dicJsonEvents[param_str] != null) { m_dicJsonEvents[param_str].Invoke(data); } m_dicJsonEvents.Remove(param_str); } } return(""); } if (RecvData != null) { return(RecvData.Invoke(hWnd, msg, param_int, param_str, data)); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(""); }