public void Connection() { try { ClientTcp.Connect(IpAdresse, Cst_PortModbus); var factory = new ModbusFactory(); ModBusMaster = factory.CreateMaster(ClientTcp); //DeleteUnexistingGroupe(); Redresseurs = Model.Redresseur.GetAllRedresseurFromAutotameId(IpAdresse); foreach (Model.Redresseur redresseur in Redresseurs) { redresseur.ModBusMaster = ModBusMaster; } Mode = MODES.Connected.ToString(); } catch (ArgumentNullException e) { Mode = MODES.Disconnected.ToString(); Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Mode = MODES.Disconnected.ToString(); Console.WriteLine("SocketException: {0}", e); } }
public static void HELP(object[] arrObj) { List <string> listParam = (List <string>)arrObj[0]; ClientTcp clientRec = (ClientTcp)arrObj[1]; clientRec.write_line("Do You want some HELP?"); }
public static void GAME_QUIT(object[] arrObj) { ClientTcp clientRec = (ClientTcp)arrObj[1]; clientRec.write_line("Bye ..."); clientRec.netStream.Close(); }
/* * private static byte[] MessageToByteArray(string message, Encoding encoding) * { * * var byteCount = encoding.GetByteCount(message); * if (byteCount > byte.MaxValue) * throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding"); * var byteArray = new byte[byteCount + 1]; * byteArray[0] = (byte)byteCount; * encoding.GetBytes(message, 0, message.Length, byteArray, 1); * return byteArray; * } */ private void Send() { string inputData = "HelloWorld "; /* var byteArray = MessageToByteArray(inputData,Encoding.ASCII); * * using (var tcpClient = new TcpClient()) * { * tcpClient.Connect("13.125.250.235",8888); * using (var networkStream = tcpClient.GetStream()) * using (var bufferedStream = new BufferedStream(networkStream)) * { * bufferedStream.Write(byteArray, 0, byteArray.Length); * // bufferedStream.Write(byteArray, 0, byteArray.Length); * // bufferedStream.Write(byteArray, 0, byteArray.Length); * } * } */ client = new ClientTcp(); // ns = client.GetStream(); byte[] bytes = new byte[1024]; byte[] sendData = Encoding.Default.GetBytes(inputData); socket.Send(bytes); socket.Send(sendData); }
// Use this for initialization void Start() { //registe bytes msg MsgManager.Instance.RegisterMsg(110, OnByteMsg); //you can registe many msg here //.... //registe protobuf msg MsgManager.Instance.RegisterMsg(typeof(TestProtobufStruct).FullName, OnProtobufMsg); //.... //connect(prefer host names) ClientTcp socket = new ClientTcp(); bool tempIsConnect = socket.Connect("www.google.com", 111); Debug.Log("是否连接成功: " + tempIsConnect); // send byte msg MsgByte tempMsg1 = new MsgByte(110); //110 is proto id tempMsg1.Write <int>(100); //write msg's body tempMsg1.Write("hello"); //write msg's body tempMsg1.Flush(); //send //send protobuf msg TestProtobufStruct testProtobufStruct = new TestProtobufStruct(); testProtobufStruct.x = 100; testProtobufStruct.y = "hello"; MsgProtobuf tempMsg2 = new MsgProtobuf(); tempMsg2.Write(testProtobufStruct); tempMsg2.Flush();//send }
private void SentFiles(ClientTcp socket) { foreach (DependenceFile dep in task.dependenceFiles) { MemoryStream memoryStream = new MemoryStream(64 * 1024); BinaryWriter writer = new BinaryWriter(memoryStream); writer.Write(dep.name); writer.Write(dep.length); writer.Write(dep.data, 0, dep.data.Length); writer.Flush(); byte[] streamSize = BitConverter.GetBytes(memoryStream.Length); socket.Sent(streamSize); socket.Sent(memoryStream.ToArray()); writer.Close(); memoryStream.Close(); if (!ReceiveFeedbackMessage(socket)) { throw new NetworkException("Problems in sent file to server"); } Debug.WriteLine("#> [DeployRpcService]: server receive file -> " + dep.name); } }
void Awake() { Instance = this; Screen.fullScreen = false; DontDestroyOnLoad(this.gameObject); ClientTcp.StartThread(); ClientUDP.StartThread(); }
// Start is called before the first frame update public void initiate() { DontDestroyOnLoad(this); UnityThread.initUnityThread(); ClientHandleData.InizializzaPacchetti(); ClientTcp.InizializzaNetwork(); }
public OpenSVGForm(ClientTcp client) { InitializeComponent(); this.svgFile = new SvgDocument(); this.parser = new SVGParser(); this.interpretor = new Interpretor(); this.myClient = client; }
static void tcpTerminal_OnLineArrival(string sLine, ClientTcp clientRec, int idxThread) { zlog.debug( "Client ID#" + clientRec.id.ToString() + " (" + clientRec.remoteIp + ":" + clientRec.remotePort.ToString() + ") " + "LineData " + sLine.Length.ToString() + " bytes +" ); ProcessCommand(sLine, clientRec); }
public Painter(ClientTcp client) { InitializeComponent(); this.g = this.pPainter.CreateGraphics(); this.tabpointF = new List <PointF>(); this.myOrder = new Orders(); this.myClient = client; debug = new Log(Constants.logPainter); }
static void tcpTerminal_OnClientDisconnected(ClientTcp clientRec) { zlog.debug( "Client ID#" + clientRec.id.ToString() + " (" + clientRec.remoteIp + ":" + clientRec.remotePort.ToString() + ") " + "Disconnected !" ); lock (hAllClient.SyncRoot) { hAllClient.Remove(clientRec.id); } zlog.debug("... Total Client = " + hAllClient.Count.ToString()); }
public static void GAME_TERMINATE(object[] arrObj) { ClientTcp clientRec = (ClientTcp)arrObj[1]; clientRec.write_line("Terminating ..."); clientRec.netStream.Close(); zlog.warning("Game Engine was request to terminate by User"); that.isQuit = true; }
//log de debug //private Log debug = null; public PainterRealTime(ClientTcp client) { InitializeComponent(); this.g = this.pPainter.CreateGraphics(); this.tabpointF = new List <PointF>(); this.myOrder = new Orders(); this.myClient = client; this.optimize = new Optimize(); //debug //this.debug = new Log(Constants.logPainterRealTime); }
public void Disconnect() { if (ClientTcp.Connected) { Mode = MODES.Disconnected.ToString(); ModbusPoolingTask.Abort(); ModBusMaster.Dispose(); ClientTcp.Close(); Redresseurs = null; } }
public override IClient GetConnection() { PeerAddressMessage peerAddressMessage = (PeerAddressMessage)ClientPeer.Peer.ReadFromSuperPeer(); MessageManager messageManager = ClientPeer.Peer.MessageManager; IPEndPoint connectionIpEndPoint = peerAddressMessage.PeerAddress.PrivateEndPoint; Client = new ClientTcp(connectionIpEndPoint, messageManager); return(Client); }
static void ProcessCommand(string sLine, ClientTcp clientRec) { List <string> lSubCmd = null; List <string> lParam = null; Action <Object[]> actionProc = null; if (CMD_TREE.TranslateCommand(sLine, ref lSubCmd, ref lParam, ref actionProc)) { if (actionProc == null) { zlog.info("Found Command & " + lParam.Count.ToString() + " Param, BUT NO ACTION Mapping"); } else { zlog.info( "Found Action Object, then Call-> " + actionProc.Method.Name + "(" + lParam.Count.ToString() + "," + "#" + clientRec.id.ToString() + ")" ); actionProc.Invoke(new object[] { lParam, clientRec }); } } else { if (lSubCmd == null) { zlog.error("Unknow or Invalid Command"); } else if (lSubCmd.Count > 0) { zlog.debug("Request next sub command: " + string.Join(",", lSubCmd.ToArray())); clientRec.write_line("Sub-command: [" + string.Join("] [", lSubCmd.ToArray()) + "]"); } else { zlog.debug("No Next Sub Command"); } } /* * if (sLine.Trim().Length < 1) { clientRec.write_line(that.Version); return; } * CMD cmd = new CMD(sLine); * if (!cmd.valid) { clientRec.write_line("Invalid Command format"); return; } * zlog.debug("CMD[" + cmd.name + "]"); * foreach (string s in cmd.param) * { * zlog.debug("Param = " + s); * } * clientRec.write_line("OK"); */ }
private bool ReceiveFeedbackMessage(ClientTcp socket) { MemoryStream ms = socket.Receive(); if (ms.Length > 0) { string message = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); return(message.Equals("ok")); } return(false); }
private int ReceiveServicePort(ClientTcp socket) { MemoryStream ms = socket.Receive(); if (ms.Length > 0) { string message = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); return(Convert.ToInt32(message.Split(new char[] { ':' })[1])); } return(-1); }
static void tcpTerminal_OnClientConnectedSuccess(ClientTcp clientRec) { zlog.debug( "Client ID#" + clientRec.id.ToString() + " (" + clientRec.remoteIp + ":" + clientRec.remotePort.ToString() + ") " + "Connected *" ); clientRec.write_line(__RTK_LOGO()); clientRec.write_line(that.Version); lock (hAllClient.SyncRoot) { hAllClient[clientRec.id] = clientRec; } zlog.debug("... Total Client = " + hAllClient.Count.ToString()); }
private void Start() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAddress = IPAddress.Parse("13.125.250.235"); IPEndPoint ipendPoint = new IPEndPoint(ipAddress, 8888); client = this; socket.Connect(ipendPoint); Send(); Debug.Log("메시지 전송"); }
//关闭服务 private void OnApplicationQuit() { print("OnApplicationQuit"); if (SceneFlag == 1) { PlayerInfo.Instance.SendPlayerInfo(); GManager.Instance.SendMessageByTcp("E1 " + UIManager.account + " "); GManager.Instance.SendMessageByUdp("E1 " + UIManager.account + " "); } ClientTcp.Close(); ClientUDP.Close(); }
//debug //private Log debug = new Log(Constants.logOrder); public void giveOrders(ClientTcp remoteClient) { this.myClient = remoteClient; // Send all orders this.myClient.Send(Constants.start); foreach (string order in orders) { this.myClient.Send(order); //debug.writeLog(order); //Console.WriteLine(order); } this.myClient.Send(Constants.stop); }
public static async Task Main() { // add server info IPEndPoint endPoint = new IPEndPoint( address: IPAddress.Parse("127.0.0.1"), port: 8080); // create listener IClient client = new ClientTcp(endPoint); // create connect with server await client.ConnectAsync(); // send message to server await client.SendMessageAsync(); }
public SocketHelper() { visionClient = new ClientTcp(IPAddress.Parse(Config.Vision.IP), Config.Vision.Port, 1024, true); visionClient.AddRules(new ReceiveDataRule { Prefix = "CAM" }); visionClient.OnServerStateChangeEvent += (s) => { StateColor = s ? "#FF11BB00" : "#FFF4F4F5"; StateText = s ? "已连接" : "未连接"; OnPropertyChanged(nameof(StateColor)); OnPropertyChanged(nameof(StateText)); OnLog?.Invoke(s ? $"[{Config.Vision.IP}:{Config.Vision.Port}] 已连接" : $"[{Config.Vision.IP}:{Config.Vision.Port}] 连接失败,尝试重新连接..."); }; visionClient.Connect(); }
public Trigger(ClientTcp client) { visionClient = client; visionClient.OnReceiveEvent += (ip, b, s) => { CamHelper.ParsingCamData(s, (cam, sid, str, data) => { Task.Run(() => { TimeoutObject.Set(); LogRead.Log.Info($"读码结果:{str}"); OnLog?.Invoke(str); OnRead?.Invoke(cam, sid, data); }); }); }; }
protected override void Run() { bool foundService = false; string requestMessage = "mpos_serv_req_wp:" + appName + ":" + appVersion; while (running && !foundService) { Debug.WriteLine("#> [DiscoveryService]: Started Discovery Service for endpoint: " + server.Type + " and app: " + appName + "/" + appVersion); foundService = true; ClientTcp socket = null; try { socket = new ClientTcp(256, false); if (server.Type == EndpointType.SECONDARY_SERVER && !MposFramework.Instance.DeviceController.IsOnline()) { throw new ConnectException("The mobile is completly offline!"); } socket.Connect(server.Ip, servicePort); Sent(socket, requestMessage); Receive(socket); } catch (Exception e) { Debug.WriteLine("## [DiscoveryService]: Error -> \n" + e.ToString()); foundService = false; } finally { if (running && !foundService) { Debug.WriteLine(">> [DiscoveryService]: Retry Discovery Service for endpoint: " + server.Type + ", in " + EndpointController.REPEAT_DISCOVERY_TASK + " ms"); Thread.Sleep(EndpointController.REPEAT_DISCOVERY_TASK); } else { Debug.WriteLine("#> [DiscoveryService]: Finished Discovery Service for endpoint: " + server.Type + " on " + server.Ip); MposFramework.Instance.EndpointController.StartDecisionMaker(server); } socket.Close(); } } }
protected override void Run() { Debug.WriteLine("#> [DeployRpcService]: Started Deploy App " + appName + "/" + appVersion + " on Remote Server (" + server.Ip + ":" + server.DeployAppPort + ")"); ClientTcp socket = null; //async programming, but run synch mode task = new DependenceFileLoadTask(); task.RunSynchronous(); try { socket = new ClientTcp(false); socket.Connect(server.Ip, server.DeployAppPort); string deployRequest = "mpos_deploy_app:" + appName + ":" + appVersion; //Debug.WriteLine("[DEBUG]: sent -> " + deployRequest); Sent(socket, deployRequest); if (!ReceiveFeedbackMessage(socket)) { throw new NetworkException("Problems in deploy request"); } string mposDependence = "mpos_dependence_size:" + task.dependenceFiles.Count; //Debug.WriteLine("[DEBUG]: sent -> " + mposDependence); Sent(socket, mposDependence); if (!ReceiveFeedbackMessage(socket)) { throw new NetworkException("Problems in deploy request"); } SentFiles(socket); server.RpcServicePort = ReceiveServicePort(socket); } catch (Exception e) { Debug.WriteLine("## [DeployRpcService]: Any problem in I/O processing!\n" + e.ToString()); } finally { Debug.WriteLine("#> [DeployRpcService]: Finished Deploy App " + appName + "/" + appVersion + " on Remote Server port: " + server.RpcServicePort); socket.Close(); } }
private void Sent(ClientTcp socket, bool manualSerialization, bool debug, object objOriginal, string methodName, object[] methodParams) { using (MemoryStream memoryStream = new MemoryStream(1024)) { using (BinaryWriter writer = new BinaryWriter(memoryStream)) { if (manualSerialization) { dataFlag = debug ? Code.CUSTOMSTREAMDEBUG : Code.CUSTOMSTREAM; writer.Write(objOriginal.GetType().FullName); writer.Write(methodName); ((RpcSerializable)objOriginal).WriteMethodParams(writer, methodName, methodParams); } else { dataFlag = debug ? Code.BSONSTREAMDEBUG : Code.BSONSTREAM; writer.Write(objOriginal.GetType().FullName); writer.Write(methodName); byte[] bsonData = BsonFormatter.Serialize(methodParams); writer.Write(bsonData.Length); writer.Write(bsonData); } writer.Flush(); byte[] headerSize = new byte[5]; headerSize[4] = dataFlag; Array.Copy(BitConverter.GetBytes(memoryStream.Length), headerSize, 4); byte[] sentStream = new byte[(int)memoryStream.Length + 5]; headerSize.CopyTo(sentStream, 0); memoryStream.ToArray().CopyTo(sentStream, headerSize.Length); socket.Sent(sentStream); } } //Debug.WriteLine(">> RpcClient Sent Data"); }
public async Task Connection() { Assert.IsNotNull(server); ClientTcp client = new ClientTcp(); Assert.IsNotNull(client); var isConnected = await client.Connect("127.0.0.1", port); Assert.IsFalse(isConnected); Assert.IsFalse(client.IsConnected); _ = Task.Run(server.StartListen); isConnected = await client.Connect("127.0.0.1", port); Assert.IsTrue(isConnected); Assert.IsTrue(client.IsConnected); }
private void EncerraConexaoTcp() { if (this.serverTcp != null) { serverTcp.EncerraConexaoTcp(); serverTcp = null; } else if (this.clientTcp != null) { clientTcp.EncerraConexaoTcp(); clientTcp = null; } }
/// <summary> /// Quando a a desistencia do jogador da partida. /// </summary> public void FimDeJogo() { //quando o jogador desiste de jogar. Quando ele desiste, envio uma msg de desistencia e fecha a conexao. //this.euDesisto = true; string msg = "19005"; if (this.serverTcp != null) { this.serverTcp.EnviaMsg(msg); this.serverTcp.EncerraConexaoTcp(); this.serverTcp = null; //Console.WriteLine("Fechou conexao server."); } else if (this.clientTcp != null) { this.clientTcp.EnviaMsg(msg); this.clientTcp.EncerraConexaoTcp(); this.clientTcp = null; //Console.WriteLine("Fechou conexao cliente."); } }
/// <summary> /// Conecta ao outro jogador como cliente. /// </summary> /// <param name="ip">Ip do outro jogador.</param> /// <param name="port">Porta do outro jogador.</param> public void ConnectToServerTcp(string ip, int port) { //Método que conecta como "cliente" ao outro jogador. this.clientTcp = new ClientTcp(this); if (clientTcp.Conecta(ip, port)) { ConexoAceita(); this.serverUdp.ParaUdp(); //this.serverUdp = null; } }