public RpcReplyMessage(byte[] recieved) { Type = MessageType.REPLY; int pos = sizeof(int); state = (ReplyState)NetUtils.ToIntFromBigEndian(recieved, sizeof(int)); pos += sizeof(int); switch (state) { case ReplyState.MSG_ACCEPTED: #region Accepted ServerVerifier = new Authentication(recieved, pos); pos += ServerVerifier.Size; if (ServerVerifier.Flavor == AuthFlavor.AUTH_NONE) { acceptState = (ReplyAcceptState)NetUtils.ToIntFromBigEndian(recieved, pos); pos += sizeof(int); switch (acceptState) { case ReplyAcceptState.SUCCESS: Result = new byte[recieved.Length - pos]; Buffer.BlockCopy(recieved, pos, Result, 0, recieved.Length - pos); break; case ReplyAcceptState.PROG_MISMATCH: PROGvLow = (uint)NetUtils.ToIntFromBigEndian(recieved, pos); pos += sizeof(int); PROGvHigh = (uint)NetUtils.ToIntFromBigEndian(recieved, pos); break; case ReplyAcceptState.PROG_UNAVAIL: case ReplyAcceptState.PROC_UNAVAIL: case ReplyAcceptState.GARBAGE_ARGS: case ReplyAcceptState.SYSTEM_ERR: break; default: throw new ArgumentException("RpcReplyMessage. Wrong Accept State."); } } else { throw new ArgumentException("RPCv2. Library not support authentication."); } #endregion break; case ReplyState.MSG_DENIED: #region Denied rejectState = (ReplyRejectState)NetUtils.ToIntFromBigEndian(recieved, pos); pos += sizeof(int); switch (rejectState) { case ReplyRejectState.RPC_MISMATCH: RPCvLow = (uint)NetUtils.ToIntFromBigEndian(recieved, pos); pos += sizeof(int); RPCvHigh = (uint)NetUtils.ToIntFromBigEndian(recieved, pos); break; case ReplyRejectState.AUTH_ERROR: authState = (AuthenticationState)NetUtils.ToIntFromBigEndian(recieved, pos); break; default: throw new ArgumentException("RpcReplyMessage. Wrong Reject State."); } #endregion break; default: throw new ArgumentException("RpcReplyMessage. Wrong Message Status."); } }
public UI_SearchWindow(ResourceModel resource) : this() { m_netUtils = new NetUtils(); m_resourceModel = resource; }
private void Awake() { _ipField.text = NetUtils.GetLocalIp(LocalAddrType.IPv4); }
/* * TODO: Fix data compression * TODO: Look into: Internal Exception: io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(2) + length(72) exceeds writerIndex(2): UnpooledHeapByteBuf(ridx: 2, widx: 2, cap: 2) */ private void HandleClientConnection(TcpClient client) { NetworkStream clientStream = client.GetStream(); ClientWrapper WrappedClient = new ClientWrapper(client); Globals.ClientManager.AddClient(ref WrappedClient); while (true) { try { if (Server.ServerSettings.UseCompression && WrappedClient.PacketMode == PacketMode.Play) { int packetLength = NetUtils.ReadVarInt(clientStream); int dataLength = NetUtils.ReadVarInt(clientStream); int actualDataLength = packetLength - NetUtils.GetVarIntBytes(dataLength).Length; ConsoleFunctions.WriteInfoLine("PacketLength: {0} \n DataLength: {1} \n ActualDataLength: {2}", packetLength, dataLength, actualDataLength); if (dataLength == 0) { if (!ReadCompressed(WrappedClient, clientStream, actualDataLength)) { break; } } else { if (!ReadUncompressed(WrappedClient, clientStream, dataLength)) { break; } } } else { if (!ReadUncompressed(WrappedClient, clientStream, NetUtils.ReadVarInt(clientStream))) { break; } } } catch (Exception ex) { ConsoleFunctions.WriteDebugLine("Error: \n" + ex); if (Server.ServerSettings.ReportExceptionsToClient) { new Disconnect(WrappedClient) { Reason = new ChatText("Server threw an exception!\n\nException: \n" + ex.Message, TextColor.Reset) }.Write(); } else { new Disconnect(WrappedClient) { Reason = new ChatText("You were kicked because of an internal problem!", TextColor.Reset) }.Write(); } break; } } Globals.DisconnectClient(WrappedClient); Thread.CurrentThread.Abort(); }
/// <summary> /// Create the requests for NTP server (default port), open socket. /// </summary> /// <param name="ntpServerAddress">NTP Server address.</param> /// <param name="onRequestComplete">callback (called from other thread!)</param> public static NtpRequest Create(string ntpServerAddress, Action <NtpPacket> onRequestComplete) { IPEndPoint endPoint = NetUtils.MakeEndPoint(ntpServerAddress, DefaultPort); return(Create(endPoint, onRequestComplete)); }
/// <summary> /// Sends the stream. /// </summary> /// <returns><c>true</c>, if stream was sent, <c>false</c> otherwise.</returns> /// <param name="o">The object you wish to send as a serialized stream.</param> /// <param name="buffsize">Max buffer size for your data.</param> public bool SendStream(object o, long buffsize) { byte error; byte[] buffer = new byte[buffsize]; Stream stream = new MemoryStream(buffer); BinaryFormatter f = new BinaryFormatter(); f.Serialize(stream, o); NetworkTransport.Send(mSocket, mConnection, NetManager.mChannelReliable, buffer, (int)stream.Position, out error); if (NetUtils.IsNetworkError(error)) { Debug.Log("NetClient::SendStream( " + o.ToString() + " , " + buffsize.ToString() + " ) Failed with reason '" + NetUtils.GetNetworkError(error) + "'."); return(false); } return(true); }
public IPEndPoint GetAddress() { return(NetUtils.CreateSocketAddr("localhost:54321")); }
/// <summary>Initialize SecondaryNameNode.</summary> /// <exception cref="System.IO.IOException"/> private void Initialize(Configuration conf, SecondaryNameNode.CommandLineOpts commandLineOpts ) { IPEndPoint infoSocAddr = GetHttpAddress(conf); string infoBindAddress = infoSocAddr.GetHostName(); UserGroupInformation.SetConfiguration(conf); if (UserGroupInformation.IsSecurityEnabled()) { SecurityUtil.Login(conf, DFSConfigKeys.DfsSecondaryNamenodeKeytabFileKey, DFSConfigKeys .DfsSecondaryNamenodeKerberosPrincipalKey, infoBindAddress); } // initiate Java VM metrics DefaultMetricsSystem.Initialize("SecondaryNameNode"); JvmMetrics.Create("SecondaryNameNode", conf.Get(DFSConfigKeys.DfsMetricsSessionIdKey ), DefaultMetricsSystem.Instance()); // Create connection to the namenode. shouldRun = true; nameNodeAddr = NameNode.GetServiceAddress(conf, true); this.conf = conf; this.namenode = NameNodeProxies.CreateNonHAProxy <NamenodeProtocol>(conf, nameNodeAddr , UserGroupInformation.GetCurrentUser(), true).GetProxy(); // initialize checkpoint directories fsName = GetInfoServer(); checkpointDirs = FSImage.GetCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointEditsDirs = FSImage.GetCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary" ); checkpointImage = new SecondaryNameNode.CheckpointStorage(conf, checkpointDirs, checkpointEditsDirs ); checkpointImage.RecoverCreate(commandLineOpts.ShouldFormat()); checkpointImage.DeleteTempEdits(); namesystem = new FSNamesystem(conf, checkpointImage, true); // Disable quota checks namesystem.dir.DisableQuotaChecks(); // Initialize other scheduling parameters from the configuration checkpointConf = new CheckpointConf(conf); IPEndPoint httpAddr = infoSocAddr; string httpsAddrString = conf.GetTrimmed(DFSConfigKeys.DfsNamenodeSecondaryHttpsAddressKey , DFSConfigKeys.DfsNamenodeSecondaryHttpsAddressDefault); IPEndPoint httpsAddr = NetUtils.CreateSocketAddr(httpsAddrString); HttpServer2.Builder builder = DFSUtil.HttpServerTemplateForNNAndJN(conf, httpAddr , httpsAddr, "secondary", DFSConfigKeys.DfsSecondaryNamenodeKerberosInternalSpnegoPrincipalKey , DFSConfigKeys.DfsSecondaryNamenodeKeytabFileKey); nameNodeStatusBeanName = MBeans.Register("SecondaryNameNode", "SecondaryNameNodeInfo" , this); infoServer = builder.Build(); infoServer.SetAttribute("secondary.name.node", this); infoServer.SetAttribute("name.system.image", checkpointImage); infoServer.SetAttribute(JspHelper.CurrentConf, conf); infoServer.AddInternalServlet("imagetransfer", ImageServlet.PathSpec, typeof(ImageServlet ), true); infoServer.Start(); Log.Info("Web server init done"); HttpConfig.Policy policy = DFSUtil.GetHttpPolicy(conf); int connIdx = 0; if (policy.IsHttpEnabled()) { IPEndPoint httpAddress = infoServer.GetConnectorAddress(connIdx++); conf.Set(DFSConfigKeys.DfsNamenodeSecondaryHttpAddressKey, NetUtils.GetHostPortString (httpAddress)); } if (policy.IsHttpsEnabled()) { IPEndPoint httpsAddress = infoServer.GetConnectorAddress(connIdx); conf.Set(DFSConfigKeys.DfsNamenodeSecondaryHttpsAddressKey, NetUtils.GetHostPortString (httpsAddress)); } legacyOivImageDir = conf.Get(DFSConfigKeys.DfsNamenodeLegacyOivImageDirKey); Log.Info("Checkpoint Period :" + checkpointConf.GetPeriod() + " secs " + "(" + checkpointConf.GetPeriod() / 60 + " min)"); Log.Info("Log Size Trigger :" + checkpointConf.GetTxnCount() + " txns"); }
public void ParseEndpointTestFail(string ipStr) { Assert.IsNull(NetUtils.ParseEndpoint(ipStr)); }
public void ParseEndpointTestSuccess(string ipStr) { Assert.AreEqual(NetUtils.ParseEndpoint(ipStr), IPEndPoint.Parse(ipStr)); }
public void GetSync(List <byte> data) { NetUtils.AddByteToList((byte)lookingAt, data); }
public void Sync(byte[] data, ref int pointerAt) { lookingAt = (LookingAt)NetUtils.GetNextByte(data, ref pointerAt); }
private void AcceptCallback(IAsyncResult res) { GeneralUtils.SetThreadCulture(); if (res.IsCompleted) { try { TcpListener listener = ((TcpListener)res.AsyncState); TcpClient client = null; try { client = listener.EndAcceptTcpClient(res); client.NoDelay = _nodelay; } finally { // Restart it if (_isStarted) { listener.BeginAcceptTcpClient(AcceptCallback, listener); } } if (ClientConnected != null) { lock (_pending) { _pending.Add(client); } _logger.LogVerbose(CANAPE.Net.Properties.Resources.TcpNetworkListener_ConnectionLogString, client.Client.RemoteEndPoint); TcpClientDataAdapter da = new TcpClientDataAdapter(client); ClientConnectedEventArgs e = new ClientConnectedEventArgs(da); NetUtils.PopulateBagFromSocket(client.Client, e.Properties); ClientConnected.Invoke(this, e); lock (_pending) { _pending.Remove(client); } } else { // There was noone to accept the message, so just close client.Close(); } } catch (ObjectDisposedException) { // Don't do anything } catch (Exception ex) { _logger.LogException(ex); } } }
void ServerUpdate(Vector3 ownerPos, Vector3 vel, byte quantBodyYaw, byte quantAimPitch, byte quantAimYaw, Vector3 FireTargetPlace, uLink.NetworkMessageInfo info) { if (!Owner.IsAlive || Owner.IsInKnockdown) { // ignore any data from client when the character is dead //ignore any data when he is in knockdown, because move is handled by server now... return; } if (info.timestamp <= serverLastTimestamp) { return; } float bodyYaw = NetUtils.DequantizeAngle(quantBodyYaw, 8); Quaternion bodyRotation = Quaternion.Euler(0, bodyYaw, 0); float aimPitch = NetUtils.DequantizeAngle(quantAimPitch, 8); float aimYaw = NetUtils.DequantizeAngle(quantAimYaw, 8); Quaternion aimRotation = Quaternion.Euler(aimPitch, aimYaw, 0); Vector3 fireDir = aimRotation * Vector3.forward; Owner.BlackBoard.Desires.Rotation = aimRotation; #if !DEADZONE_CLIENT ServerAnticheat.ReportMove(Owner.NetworkView.owner, ownerPos, vel, info); #endif //TODO remove/reimplement this is a very naive code. The server accepts the position from the client but limits the speed at the same time. //The only benefit I can see that the character will not move too fast once a no more messages will come from its client. if (vel.sqrMagnitude > sqrMaxServerSpeed) { vel.x = vel.y = vel.z = Mathf.Sqrt(sqrMaxServerSpeed) / 3.0f; } //float deltaTime = (float)( info.timestamp - serverLastTimestamp ); //Vector3 deltaPos = vel * deltaTime; if (applyTransformations) { //m_Transform.rotation = bodyRotation; m_Transform.localRotation = bodyRotation; // character.Move( deltaPos ); // HACK for now } //m_Transform.position = ownerPos; m_Transform.localPosition = ownerPos; // TODO Hack, this means the server is no longer authoritative. rotation = bodyRotation; velocity = vel; Owner.BlackBoard.Desires.FireDirection = Owner.BlackBoard.FireDir = fireDir; Owner.BlackBoard.Desires.FireTargetPlace = FireTargetPlace; serverLastTimestamp = info.timestamp; /*Vector3 serverPos = m_Transform.position; * Vector3 diff = serverPos - ownerPos;*/ /* * if( Vector3.SqrMagnitude( diff ) > sqrMaxServerError ) * { #if USE_RPC_INSTEAD_UNRELIABLERPC * networkView.RPC( "AdjustOwnerPos", uLink.RPCMode.Owner, serverPos ); #else * networkView.UnreliableRPC( "AdjustOwnerPos", uLink.RPCMode.Owner, serverPos ); #endif //USE_RPC_INSTEAD_UNRELIABLERPC * * } * else * { #if USE_RPC_INSTEAD_UNRELIABLERPC * networkView.RPC( "GoodOwnerPos", uLink.RPCMode.Owner ); #else * networkView.UnreliableRPC( "GoodOwnerPos", uLink.RPCMode.Owner ); #endif // USE_RPC_INSTEAD_UNRELIABLERPC * } * */ if (velocity.sqrMagnitude > Mathf.Epsilon) { Owner.cbServerUserInput(); } }
public override IPEndPoint GetBindAddress() { return(NetUtils.CreateSocketAddr("localhost:9876")); }
public static IPEndPoint GetHttpAddress(Configuration conf) { return(NetUtils.CreateSocketAddr(conf.GetTrimmed(DFSConfigKeys.DfsNamenodeSecondaryHttpAddressKey , DFSConfigKeys.DfsNamenodeSecondaryHttpAddressDefault))); }
/// <summary> /// Creates an HTTP 307 response with the redirect location set back to the /// test server's address. /// </summary> /// <remarks> /// Creates an HTTP 307 response with the redirect location set back to the /// test server's address. HTTP is supposed to terminate newlines with CRLF, so /// we hard-code that instead of using the line separator property. /// </remarks> /// <returns>String HTTP 307 response</returns> private string TemporaryRedirect() { return("HTTP/1.1 307 Temporary Redirect\r\n" + "Location: http://" + NetUtils.GetHostPortString (nnHttpAddress) + "\r\n" + "\r\n"); }
public virtual string GetHostAndPort() { // SecondaryNameNodeInfoMXXBean return(NetUtils.GetHostPortString(nameNodeAddr)); }
public override void Update() { Join.color = Color.FloralWhite; Back.color = Color.FloralWhite; if (TakeIP) { string str = IPText.text; GUIInput.AppendString(ref str, 15); IPText.text = str; Caret.position = IPText.position + new Vector2(IPText.size.x / 2 - 0.005f, CaretOffset); } if (TakePort) { string str = PortText.text; GUIInput.AppendString(ref str, 5); PortText.text = str; Caret.position = PortText.position + new Vector2(PortText.size.x / 2 - 0.005f, CaretOffset); } if (Input.GetMouseButtonUp(Input.MouseButtons.LEFT)) { TakePort = false; TakeIP = false; TextBoxIP.color = Color.Black; TextBoxPort.color = Color.Black; if (Blink == null) { Blink = CaretBlink(); StartCoroutine(Blink); } } if (Join.Clicked()) { TakeIP = false; TakePort = false; ConnectingText.text = ""; System.Net.IPAddress ipaddress; UserSettings.AddOrUpdateAppSetting("LastUsedIP", IPText.text); try { ipaddress = NetUtils.ResolveAddress(IPText.text); } catch (Exception e) { ConnectingText.text = e.Message; return; } if (PortText.text != "") { try { if (IPText.text == "127.0.0.1") { MatchSystem.instance.LocalPort = 0; } else { MatchSystem.instance.LocalPort = Convert.ToInt32(PortText.text); } MatchSystem.instance.TargetPort = Convert.ToInt32(PortText.text); MatchSystem.instance.TargetIP = IPText.text; MatchSystem.instance.Listener.AllPeersConnectedEvent += Listener_AllPeersConnectedEvent; MatchSystem.instance.Listener.PeerDisconnectedEvent += Listener_PeerDisconnectedEvent; MatchSystem.instance.Init(); MatchSystem.instance.Connect(); ConnectingText.text = "Connecting"; ConnectingText.scale = new Vector2(1); ConnectingText.position = new Vector2(0.75f, 0.9f); Connect = Connecting(); StartCoroutine(Connect); Join.interactable = false; return; } catch (Exception e) //Hopefully this catches the exception thrown in ServerInfoEventHandler { ConnectingText.text = e.Message; Join.interactable = true; StopCoroutine(Connect); } } else { if (IPText.text == "") { TextBoxIP.color = Color.Red; } if (PortText.text == "") { TextBoxPort.color = Color.Red; } } } if (Back.Clicked()) { TakeIP = false; TakePort = false; CameraMaster.instance.SetState(CAM_STATE.MAIN_MENU); ConnectingText.text = ""; UserSettings.AddOrUpdateAppSetting("LastUsedIP", IPText.text); } if (TextBoxIP.Clicked()) { ConnectingText.text = ""; TakeIP = true; if (ClearIP) { IPText.text = ""; ClearIP = false; } } else if (TextBoxPort.Clicked()) { ConnectingText.text = ""; TakePort = true; if (ClearPort) { PortText.text = ""; ClearPort = false; } } else if (Input.GetMouseButtonUp(Input.MouseButtons.LEFT)) { if (Blink != null) { StopCoroutine(Blink); Blink = null; Caret.text = ""; } } if (Join.Hovered()) { Join.color = Color.IndianRed; } else if (Back.Hovered()) { Back.color = Color.IndianRed; } }
/// <summary> /// Connect the specified ip and port. /// </summary> /// <param name="ip">Ip.</param> /// <param name="port">Port.</param> public bool Connect(string ip, int port) { byte error; mConnection = NetworkTransport.Connect(mSocket, ip, port, 0, out error); if (NetUtils.IsNetworkError(error)) { Debug.Log("NetClient::Connect( " + ip + " , " + port.ToString() + " ) Failed with reason '" + NetUtils.GetNetworkError(error) + "'."); return(false); } mServerIP = ip; mPort = port; return(true); }
public bool Down(string filePath, ref byte[] lrcData, int iThread) { System.Net.ServicePointManager.DefaultConnectionLimit = iThread; string RequestURL = "http://music.163.com/api/search/get/web?csrf_token="; string ResponseURL = "http://music.163.com/api/song/lyric?os=osx&id="; var m_tools = new NetUtils(); var m_info = new MusicInfo(filePath); try { string postStr = "&s=" + m_tools.URL_Encoding(m_info.Title, Encoding.UTF8) + "&type=1&offset=0&total=true&limit=5"; string resultJson = m_tools.Http_Post(RequestURL, postStr); if (resultJson.Equals("")) { return(false); } // 获得歌曲ID JObject jsonSID = JObject.Parse(resultJson); JArray jsonArraySID = (JArray)jsonSID["result"]["songs"]; string sid = null; // 二级匹配 bool flag = false; foreach (var item in jsonArraySID) { if (item["artists"][0]["name"].ToString() == m_info.Singer) { sid = item["id"].ToString(); flag = true; } } if (!flag) { sid = jsonArraySID[0]["id"].ToString(); } string lrcUrl = ResponseURL + sid + "&lv=-1&kv=-1&tv=-1"; string lrcString = m_tools.Http_Get(lrcUrl, Encoding.UTF8, true); // 从Json当中分析歌词信息 JObject lrcObject = JObject.Parse(lrcString); string lrcDataString = lrcObject["lrc"]["lyric"].ToString(); if (lrcDataString.Equals("")) { return(false); } // 去掉网易时间轴后一位 Regex reg = new Regex(@"\[\d+:\d+.\d+\]"); string deal_ok = reg.Replace(lrcDataString, new MatchEvaluator((Match machs) => { string time = machs.ToString(); return(time.Remove(time.Length - 2, 1)); })); // 将字符串转换为字节流进行存储 lrcData = Encoding.UTF8.GetBytes(deal_ok); return(true); } catch (Exception) { return(false); } }
void Update() { //CURRENT STATE: WAIT FOR THE USER TO ENTER SETUP INFORMATION if (clientAuto.CurrState == PongClientAutomaton.WAIT_USER_SETUP_INFO) { //if the Role has been assigned if (GeneralUtils.RoleChosen()) { //enact transition to the next state clientAuto.Transition(PongClientAutomaton.TRY_CONNECT_SERVER); } } //CURRENT STATE: TRY TO CONNECT TO THE SERVER else if (clientAuto.CurrState == PongClientAutomaton.TRY_CONNECT_SERVER) { //initiate connection clientSocket = new ClientSocket(NetUtils.GetMyClientPort(), 1, serverIP); //if connected successfully if (clientSocket.Connected) { //enact transition to the next state clientAuto.Transition(PongClientAutomaton.WAIT_RECV_ENV_SETTINGS); } } //CURRENT STATE: WAIT TO RECV ENVIRONMENT SETTINGS FROM SERVER else if (clientAuto.CurrState == PongClientAutomaton.WAIT_RECV_ENV_SETTINGS) { //if received something from server if (clientSocket.pollAndReceiveData(clientSocket.Client, recvdData, 10) >= 1) { //extract the json part of the message string jsonString = recvdData.timeStamp.Substring(recvdData.timeStamp.IndexOf(",") + 1); envState = JsonConvert.DeserializeObject <EnvState>(jsonString); //respond with acknowledgement clientSocket.sendData(new StreamData("00:00:00")); //store communication time begin for Throughput analysis if (doAnalysis) { Tb = DateTime.Now; } //enact transition to the next state clientAuto.Transition(PongClientAutomaton.NORMAL_COMMUNICATION); } } //CURRENT STATE: NORMAL COMMUNICATION WITH THE SERVER else if (clientAuto.CurrState == PongClientAutomaton.NORMAL_COMMUNICATION) { //if received something from server if (clientSocket.pollAndReceiveData(clientSocket.Client, recvdData, 10) >= 1) { //extract the json part of the message //Debug.Log ( "recvd = " + recvdData.timeStamp ); string jsonString = recvdData.timeStamp.Substring(recvdData.timeStamp.IndexOf(",") + 1); envState = JsonConvert.DeserializeObject <EnvState>(jsonString); //update the environment to reflect the contents of the EnvState object GeneralUtils.SetEnvState(envState); //get human input InputData inputData = GeneralUtils.PackageInputData(); if (inputData == null) { inputData = new InputData(); } //send InputData to the server string message = "InputData," + inputData.ToJsonString(); StreamData dataToSend = new StreamData(message); clientSocket.sendData(dataToSend); //increment Throughpput counter N if (doAnalysis) { N += 1; } } //if user stops, stop Throughput analysis if (doAnalysis && Input.GetKeyDown(KeyCode.C)) { Te = DateTime.Now; T = ((float)N / (float)(Te - Tb).TotalSeconds); string outputFileName = GeneralUtils.GetTAFileName(); StreamWriter sw = new StreamWriter(outputFileName, true); sw.Write(T.ToString() + "," + N.ToString() + "," + Tb.ToString().Replace(",", "_") + "," + Te.ToString().Replace(",", "_")); sw.Close(); } //if the connection is lost if (!clientSocket.Connected) { //enact transition to the next state clientAuto.Transition(PongClientAutomaton.ERROR_STATE); } } //CURRENT STATE: ERROR OCCURRED else if (clientAuto.CurrState == PongClientAutomaton.ERROR_STATE) { } }
static ushort Read_U16(byte[] buffer, Stream gs) { ReadFully(gs, buffer, sizeof(ushort)); return(NetUtils.ReadU16(buffer, 0)); }
public UI_SearchWindow() { m_netUtils = new NetUtils(); InitializeComponent(); }
private void TestPbClientFactory() { IPEndPoint addr = new IPEndPoint(0); System.Console.Error.WriteLine(addr.GetHostName() + addr.Port); Configuration conf = new Configuration(); MRClientProtocol instance = new TestRPCFactories.MRClientProtocolTestImpl(this); Server server = null; try { server = RpcServerFactoryPBImpl.Get().GetServer(typeof(MRClientProtocol), instance , addr, conf, null, 1); server.Start(); System.Console.Error.WriteLine(server.GetListenerAddress()); System.Console.Error.WriteLine(NetUtils.GetConnectAddress(server)); MRClientProtocol client = null; try { client = (MRClientProtocol)RpcClientFactoryPBImpl.Get().GetClient(typeof(MRClientProtocol ), 1, NetUtils.GetConnectAddress(server), conf); } catch (YarnRuntimeException e) { Sharpen.Runtime.PrintStackTrace(e); NUnit.Framework.Assert.Fail("Failed to crete client"); } } catch (YarnRuntimeException e) { Sharpen.Runtime.PrintStackTrace(e); NUnit.Framework.Assert.Fail("Failed to crete server"); } finally { server.Stop(); } }
public static void Start() { IPEndPoint address = new IPEndPoint(0); Configuration configuration = new Configuration(); ResourceTracker instance = new TestResourceTrackerPBClientImpl.ResourceTrackerTestImpl (); server = RpcServerFactoryPBImpl.Get().GetServer(typeof(ResourceTracker), instance , address, configuration, null, 1); server.Start(); client = (ResourceTracker)RpcClientFactoryPBImpl.Get().GetClient(typeof(ResourceTracker ), 1, NetUtils.GetConnectAddress(server), configuration); }
/// <summary> /// 开启使用Udp动态获取局域网中的主机 /// </summary> protected static void BeginDynamic() { NetUtils.UDPBroadCast(new Msg(1, HoldingServer.Self), Configuration.Port); Thread.Sleep(Configuration.Timeout); }