private void button1_Click(object sender, EventArgs e) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 }); var ControllerPort = 40001; var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort); _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var header = "@"; var command = "00C"; var checksum = "E3"; var end = "\r\n"; var data = header + command + checksum + end; byte[] bytes = new byte[1024]; //Start Connect _connectDone.Reset(); watch.Start(); _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client); //wait 2s _connectDone.WaitOne(2000, false); var text = (_client.Connected) ? "ok" : "ng"; richTextBox1.AppendText(text + "\r\n"); watch.Stop(); richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n"); }
public void Test_Default() { var config = new ClientConfiguration(); Assert.AreEqual(1, config.BucketConfigs.Count); var bucketConfig = config.BucketConfigs.First().Value; IPAddress ipAddress; IPAddress.TryParse("127.0.0.1", out ipAddress); var endPoint = new IPEndPoint(ipAddress, bucketConfig.Port); Assert.AreEqual(endPoint, bucketConfig.GetEndPoint()); Assert.IsEmpty(bucketConfig.Password); Assert.IsEmpty(bucketConfig.Username); Assert.AreEqual(11210, bucketConfig.Port); Assert.AreEqual("default", bucketConfig.BucketName); Assert.AreEqual(2, bucketConfig.PoolConfiguration.MaxSize); Assert.AreEqual(1, bucketConfig.PoolConfiguration.MinSize); Assert.AreEqual(2500, bucketConfig.PoolConfiguration.RecieveTimeout); Assert.AreEqual(2500, bucketConfig.PoolConfiguration.OperationTimeout); Assert.AreEqual(10000, bucketConfig.PoolConfiguration.ShutdownTimeout); Assert.AreEqual(2500, bucketConfig.DefaultOperationLifespan); Assert.AreEqual(75000, config.ViewRequestTimeout); }
public server_socket( Object name, int port ) : base() { try { /* _server_socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); */ /* _server_socket.Bind( new IPEndPoint( 0, port ) ); */ IPEndPoint endpoint; if( name != bigloo.foreign.BFALSE ) { String server = bigloo.foreign.newstring( name ); IPHostEntry host = Dns.Resolve(server); IPAddress address = host.AddressList[0]; endpoint = new IPEndPoint(address, port); } else { endpoint = new IPEndPoint( 0, port ); } _server_socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); _server_socket.Bind( endpoint ); _server_socket.Listen( 10 ); } catch (Exception e) { socket_error( "make-server-socket", "cannot create socket (" + e.Message + ")", new bint( port ) ); } }
private static void Server() { list = new List<IPAddress>(); const ushort data_size = 0x400; // = 1024 byte[] data; while (ServerRun) { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort); try { sock.Bind(iep); EndPoint ep = (EndPoint)iep; data = new byte[data_size]; if (!ServerRun) break; int recv = sock.ReceiveFrom(data, ref ep); string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); data = new byte[data_size]; if (!ServerRun) break; recv = sock.ReceiveFrom(data, ref ep); stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); sock.Close(); } catch { } } }
internal void InitConnect(IPEndPoint serverEndPoint, Action<IPEndPoint, Socket> onConnectionEstablished, Action<IPEndPoint, SocketError> onConnectionFailed, ITcpConnection connection, TimeSpan connectionTimeout) { if (serverEndPoint == null) throw new ArgumentNullException("serverEndPoint"); if (onConnectionEstablished == null) throw new ArgumentNullException("onConnectionEstablished"); if (onConnectionFailed == null) throw new ArgumentNullException("onConnectionFailed"); var socketArgs = _connectSocketArgsPool.Get(); var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socketArgs.RemoteEndPoint = serverEndPoint; socketArgs.AcceptSocket = connectingSocket; var callbacks = (CallbacksStateToken) socketArgs.UserToken; callbacks.OnConnectionEstablished = onConnectionEstablished; callbacks.OnConnectionFailed = onConnectionFailed; callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout)); AddToConnecting(callbacks.PendingConnection); try { var firedAsync = connectingSocket.ConnectAsync(socketArgs); if (!firedAsync) ProcessConnect(socketArgs); } catch (ObjectDisposedException) { HandleBadConnect(socketArgs); } }
public static void Main() { using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // Addressing IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress); IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port); // Connecting Debug.Print("Connecting to server " + serverEndPoint + "."); clientSocket.Connect(serverEndPoint); Debug.Print("Connected to server."); using (SslStream sslStream = new SslStream(clientSocket)) { X509Certificate rootCA = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA)); X509Certificate clientCert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA)); sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert clientCert, // Authenticate client new X509Certificate[] { rootCA }, // CA certs for verification SslVerification.CertificateRequired, // Verify server SslProtocols.Default // Protocols that may be required ); // Sending byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!"); sslStream.Write(messageBytes, 0, messageBytes.Length); } }// the socket will be closed here }
public void ConnectIPAddressAny () { IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0); /* UDP sockets use Any to disconnect try { using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { s.Connect (ep); s.Close (); } Assert.Fail ("#1"); } catch (SocketException ex) { Assert.AreEqual (10049, ex.ErrorCode, "#2"); } */ try { using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect (ep); s.Close (); } Assert.Fail ("#3"); } catch (SocketException ex) { Assert.AreEqual (10049, ex.ErrorCode, "#4"); } }
static void Main(string[] args) { byte[] receiveBytes = new byte[1024]; int port =8080;//服务器端口 string host = "10.3.0.1"; //服务器ip IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 Console.WriteLine("Starting Creating Socket Object"); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket sender.Connect(ipe);//连接到服务器 string sendingMessage = "Hello World!"; byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]"); sender.Send(forwardingMessage); int totalBytesReceived = sender.Receive(receiveBytes); Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived)); //byte[] bs = Encoding.ASCII.GetBytes(sendStr); sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.ReadLine(); }
public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, TcpClientConnector connector, TimeSpan connectionTimeout, Action<ITcpConnection> onConnectionEstablished, Action<ITcpConnection, SocketError> onConnectionFailed, bool verbose) { var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose); // ReSharper disable ImplicitlyCapturedClosure connector.InitConnect(remoteEndPoint, (_, socket) => { if (connection.InitSocket(socket)) { if (onConnectionEstablished != null) onConnectionEstablished(connection); connection.StartReceive(); connection.TrySend(); } }, (_, socketError) => { if (onConnectionFailed != null) onConnectionFailed(connection, socketError); }, connection, connectionTimeout); // ReSharper restore ImplicitlyCapturedClosure return connection; }
static void Main(string[] args) { var m_Config = new ServerConfig { Port = 911, Ip = "Any", MaxConnectionNumber = 1000, Mode = SocketMode.Tcp, Name = "CustomProtocolServer" }; var m_Server = new CustomProtocolServer(); m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory()); m_Server.Start(); EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(serverAddress); var socketStream = new NetworkStream(socket); var reader = new StreamReader(socketStream, Encoding.ASCII, false); string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty) + Guid.NewGuid().ToString().Replace("-", string.Empty) + Guid.NewGuid().ToString().Replace("-", string.Empty); Random rd = new Random(); var watch = Stopwatch.StartNew(); for (int i = 0; i < 10; i++) { int startPos = rd.Next(0, charSource.Length - 2); int endPos = rd.Next(startPos + 1, charSource.Length - 1); var currentMessage = charSource.Substring(startPos, endPos - startPos + 1); byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO"); socketStream.Write(requestNameData, 0, requestNameData.Length); var data = Encoding.ASCII.GetBytes(currentMessage); socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2); socketStream.Write(data, 0, data.Length); socketStream.Flush(); // Console.WriteLine("Sent: " + currentMessage); var line = reader.ReadLine(); //Console.WriteLine("Received: " + line); //Assert.AreEqual(currentMessage, line); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds); } Console.ReadLine(); }
/* // TODO: Асинхронная отправка! Или не нужно? /// <summary> /// Отправить единичное сообщение на единичный хост /// </summary> /// <param name="text">Текст сообщения</param> // internal static void SendMessage(string RemoteHost, string text) { TcpClient client = null; NetworkStream networkStream = null; try { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000); // TODO : заменить 127.0.0.1 на что-то более верное // TODO: добавить динамическое выделение портов (из пула свободных портов) // получатель сообщения при IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000); // TODO :забить номера портов в настройки client = new TcpClient(localEndPoint); client.Connect(remoteEndPoint); networkStream = client.GetStream(); byte[] sendBytes = Encoding.UTF8.GetBytes(text); networkStream.Write(sendBytes, 0, sendBytes.Length); byte[] bytes = new byte[client.ReceiveBufferSize]; networkStream.Read(bytes, 0, client.ReceiveBufferSize); string returnData = Encoding.UTF8.GetString(bytes); //MessageBox.Show(returnData); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (networkStream != null) networkStream.Close(); if (client!=null) client.Close(); } } */ // реализаця с UDP internal static void SendMessage(string RemoteHost, string text) { UdpClient client = null; try { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000); // получатель сообщения при IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000); // TODO :забить номера портов в настройки client = new UdpClient(localEndPoint); byte[] sendBytes = Encoding.ASCII.GetBytes(text); networkStream.Write(sendBytes, 0, sendBytes.Length); byte[] bytes = new byte[client.ReceiveBufferSize]; networkStream.Read(bytes, 0, client.ReceiveBufferSize); string returnData = Encoding.UTF8.GetString(bytes); //MessageBox.Show(returnData); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (networkStream != null) networkStream.Close(); if (client != null) client.Close(); } }
/// <summary> /// Gets a list of variable binds. /// </summary> /// <param name="version">Protocol version.</param> /// <param name="endpoint">Endpoint.</param> /// <param name="community">Community name.</param> /// <param name="variables">Variable binds.</param> /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param> /// <returns></returns> public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (community == null) { throw new ArgumentNullException("community"); } if (variables == null) { throw new ArgumentNullException("variables"); } if (version == VersionCode.V3) { throw new NotSupportedException("SNMP v3 is not supported"); } var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables); var response = message.GetResponse(timeout, endpoint); var pdu = response.Pdu(); if (pdu.ErrorStatus.ToInt32() != 0) { throw ErrorException.Create( "error in response", endpoint.Address, response); } return pdu.Variables; }
internal void Send(byte[] data, IPEndPoint receiver) { lock (UDPSocket) { UDPSocket.SendTo(data, receiver); } }
public void Connect(IPEndPoint address) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = address; args.Completed += new EventHandler<SocketAsyncEventArgs>(socket_Connected); socket.ConnectAsync(args); }
partial void OpenSocket(string connectedHost, uint connectedPort) { var ep = new IPEndPoint(Dns.GetHostEntry(connectedHost).AddressList[0], (int)connectedPort); this._socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); this._socket.Connect(ep); this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1); }
private TcpClient ConnectRemote(IPEndPoint ipEndPoint) { TcpClient client = new TcpClient(); try { client.Connect(ipEndPoint); } catch (SocketException socketException) { if (socketException.SocketErrorCode == SocketError.ConnectionRefused) { throw new ProducerException("服务端拒绝连接", socketException.InnerException ?? socketException); } if (socketException.SocketErrorCode == SocketError.HostDown) { throw new ProducerException("订阅者服务端尚未启动", socketException.InnerException ?? socketException); } if (socketException.SocketErrorCode == SocketError.TimedOut) { throw new ProducerException("网络超时", socketException.InnerException ?? socketException); } throw new ProducerException("未知错误", socketException.InnerException ?? socketException); } catch (Exception e) { throw new ProducerException("未知错误", e.InnerException ?? e); } return client; }
public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint) { _connectTcs = new TaskCompletionSource<Socket>(); var task = _connectTcs.Task; Connect(remoteEndPoint); return task; }
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint) { _remoteEndPoint = remoteEndPoint; _localEndPoint = localEndPoint; Debug.Assert(length == 0); try { _ssl = new SslStream(_inputStream, true); _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) => { var self = (SslTransportHandler)selfObject; if (t.IsFaulted || t.IsCanceled) self._next.FinishAccept(null, 0, 0, null, null); else self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) => { var self2 = (SslTransportHandler)selfObject2; if (t2.IsFaulted || t2.IsCanceled) self2._next.FinishAccept(null, 0, 0, null, null); else self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint); }, self); }, this); } catch (Exception) { Callback.StartDisconnect(); } }
internal GatewayAcceptor(MessageCenter msgCtr, Gateway gateway, IPEndPoint gatewayAddress) : base(msgCtr, gatewayAddress, SocketDirection.GatewayToClient) { this.gateway = gateway; loadSheddingCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_LOAD_SHEDDING); gatewayTrafficCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_RECEIVED); }
public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null) { _buffer = new byte[8192]; _bufferIndex = 0; _read = 0; _responseType = ResponseType.Unknown; _uri = uri; IPAddress ip; var headersString = string.Empty; var contentLength = data != null ? data.Length : 0; if (headers != null && headers.Any()) headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim())); if (_uri.HostNameType == UriHostNameType.Dns) { var host = Dns.GetHostEntry(_uri.Host); ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork); } else { ip = IPAddress.Parse(_uri.Host); } _endPoint = new IPEndPoint(ip, _uri.Port); _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n"); if (data == null) return; var tmpRequest = new byte[_request.Length + data.Length]; Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length); Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length); _request = tmpRequest; }
private void listen() { UdpClient uc = new UdpClient(9527);//udp协议添加端口号 while (true) { IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0);//将网络端点转化为ip地址 和端口号 byte[] bmsg = uc.Receive(ref ipep);//返回有远程主机发出的udp数据报 string msg = Encoding.Default.GetString(bmsg);//将字节转化为文本 string[] s = msg.Split('|');//元素分隔 if(s.Length != 4) { continue; } if(s[0]=="LOGIN") { Friend friend=new Friend(); int curIndex = Convert.ToInt32(s[2]); if (curIndex<0 || curIndex>=this.ilHeadImages.Images.Count) { curIndex = 0; } friend.HeadImageIndex =curIndex; friend.NickName = s[1]; friend.Shuoshuo=s[3]; object[] pars=new object[1]; pars[0]=friend; this.Invoke(new delAddFriend(this.addUcf),pars[0]); } } }
protected void serverLoop() { Trace.WriteLine("Waiting for UDP messages."); listener = new UdpClient(UDP_PORT); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT); byte[] receive_byte_array; bool running = true; while (running) { try { receive_byte_array = listener.Receive(ref groupEP); if (receive_byte_array.Length != 2) { Trace.WriteLine("Invalid UDP message received. Ignored message!"); continue; } Trace.WriteLine("Upp fan speed message received."); int fan = receive_byte_array[0]; byte speed = receive_byte_array[1]; fanControlDataObject.setPinSpeed(fan, speed, true); } catch { running = false; } } }
static void Main(string[] args) { //TODO: 1. Utworzenie punktu połączenia do serwera - IPEndPoint var punktSerwer = new IPEndPoint(IPAddress.Parse("192.168.1.163"), 2000); //TODO: 2. Utworzenie gniazda połączenia - Socket var gniazdoSerwer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //TODO: 3. Połączenie z serwerem - Socket.Connect gniazdoSerwer.Connect(punktSerwer); //połączenie z serwerem //TODO: 4. Pobranie danych z serwera - Socket.Receive(ASCIIEncoding) var tablicaDane = new byte[64]; //Bajt gniazdoSerwer.Receive(tablicaDane); //Oczekiwanie i pobranie danych Console.WriteLine(Encoding.UTF8.GetString(tablicaDane)); var watek = new Thread(WysylanieCzat); //wątek dla nadłuchiwania z klawiatury i wysyłania do serwera watek.IsBackground = true; watek.Start(gniazdoSerwer); while (true) //pętla dla obierania wiadomości { var dane = new byte[512]; //256 -> 3 znaki + 253 spacje gniazdoSerwer.Receive(dane); Console.WriteLine(Encoding.UTF8.GetString(dane)); } //Kod - klient równocześnie wysyła i odbiera komunikaty }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) return; InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket IPEndPoint iep = null; iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize; m_socket.SendBufferSize = m_configuration.SendBufferSize; m_socket.Blocking = false; m_socket.Bind(ep); IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound); m_listenPort = boundEp.Port; m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; NetRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } #endif byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0); m_status = NetPeerStatus.Running; } }
private TcpConnectionLockless(Guid connectionId, IPEndPoint remoteEndPoint, bool verbose): base(remoteEndPoint) { Ensure.NotEmptyGuid(connectionId, "connectionId"); _connectionId = connectionId; _verbose = verbose; }
public void TestStreamingTransportServer() { BlockingCollection<string> queue = new BlockingCollection<string>(); List<string> events = new List<string>(); IStreamingCodec<string> stringCodec = _injector.GetInstance<StringStreamingCodec>(); IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); var remoteHandler = Observer.Create<TransportEvent<string>>(tEvent => queue.Add(tEvent.Data)); using (var server = new StreamingTransportServer<string>(endpoint.Address, remoteHandler, _tcpPortProvider, stringCodec)) { server.Run(); IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), server.LocalEndpoint.Port); using (var client = new StreamingTransportClient<string>(remoteEndpoint, stringCodec)) { client.Send("Hello"); client.Send(", "); client.Send("World!"); events.Add(queue.Take()); events.Add(queue.Take()); events.Add(queue.Take()); } } Assert.Equal(3, events.Count); Assert.Equal(events[0], "Hello"); Assert.Equal(events[1], ", "); Assert.Equal(events[2], "World!"); }
private static bool Discover() { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); byte[] data = Encoding.ASCII.GetBytes(req); IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900); byte[] buffer = new byte[0x1000]; DateTime start = DateTime.Now; try { do { s.SendTo(data, ipe); s.SendTo(data, ipe); s.SendTo(data, ipe); int length = 0; do { length = s.Receive(buffer); string resp = Encoding.ASCII.GetString(buffer, 0, length); if (resp.Contains("upnp:rootdevice")) { resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9); resp = resp.Substring(0, resp.IndexOf("\r")).Trim(); if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp))) { _descUrl = resp; return true; } } } while (length > 0); } while (start.Subtract(DateTime.Now) < _timeout); return false; } catch { return false; } }
internal static AgentProfile Create(Guid id, VersionCode version, IPEndPoint agent, string getCommunity, string setCommunity, string agentName, string authenticationPassphrase, string privacyPassphrase, int authenticationMethod, int privacyMethod, string userName, int timeout) { if (version == VersionCode.V3) { return new SecureAgentProfile( id, version, agent, agentName, authenticationPassphrase, privacyPassphrase, authenticationMethod, privacyMethod, userName, timeout); } return new NormalAgentProfile( id, version, agent, new OctetString(getCommunity), new OctetString(setCommunity), agentName, userName, timeout); }
/// <summary> /// Constructs an instance of the StreamAssembled class. /// </summary> /// <param name="remoteIPEndPoint">The IPEndPoint of the sender.</param> /// <param name="headerSize">The size of the header.</param> public StreamAssembled(IPEndPoint remoteIPEndPoint, int headerSize) { this._started = GenuineUtility.TickCount; this.RemoteIPEndPoint = remoteIPEndPoint; this._headerSize = headerSize; this._readPosition = headerSize; }
public void Connect(IPEndPoint remoteAddress) { BaseSocket = new TcpClient(); BaseSocket.Connect(remoteAddress); OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream())); InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream())); }
public Connector(TcpService service, TcpServiceConfig.ClientConfig config, Object token) { _service = service; _config = config; _token = token; System.Net.IPAddress addr; System.Net.IPAddress.TryParse(_config.ip, out addr); EndPoint = new System.Net.IPEndPoint(addr, _config.port); }
public SipMessageEventArgs(string sipMsg, NET.IPEndPoint remoteEp) { if (null == sipMsg) { throw new ArgumentNullException("sipMsg"); } m_SipMsg = sipMsg; m_RemoteEp = remoteEp; }
void Connect() { Debug.Log("Connect"); System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(m_IPAdress); System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, m_port); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_singleton = this; m_socket.Connect(remoteEndPoint); }
public new void BeginConnect(n.EndPoint endpoint, AsyncCallback ac, object st) { n.IPEndPoint ipep = endpoint as n.IPEndPoint; if (endpoint == null) { throw new Exception("Sorry, guy... but this isn't in the scope of this class's purpose."); } attemptedConnectionEndpoint = ipep.Address.ToString(); base.BeginConnect(endpoint, ac, st); }
private void StartFtp() { if (!RoleEnvironment.IsEmulated) { InitContext(); System.Net.IPEndPoint ep = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Ftp"].IPEndpoint; new FtpHelper(RoleEnvironment.GetLocalResource("Storage").RootPath, IPAddress(), ep.Port).Start(); } }
/// <summary> /// Get the connection, if any, for a certain remote endpoint /// </summary> public NetConnection GetConnection(NetEndPoint ep) { NetConnection retval; // this should not pose a threading problem, m_connectionLookup is never added to concurrently // and TryGetValue will not throw an exception on fail, only yield null, which is acceptable m_connectionLookup.TryGetValue(ep, out retval); return(retval); }
public RtpMessageEventArgs(byte[] rtpData, NET.IPEndPoint remoteEp) { if (null == rtpData) { throw new ArgumentNullException("rtpData"); } m_RtpData = rtpData; m_RemoteEp = remoteEp; }
public void Init(System.Net.IPEndPoint inServerAddress, string inName, byte inWorldId) { base.Init(core.World.DefaultWorldCount); // client NetPeerConfiguration config = new NetPeerConfiguration("game", inServerAddress.AddressFamily); #if DEBUG // 디버깅 환경에서 타임 아웃 처리 조정 config.ConnectionTimeout = 300f; //if (Configuration.Instance.EnableLatencySimulation) //{ // config.SimulatedLoss = Configuration.Instance.SimulatedLoss; // config.SimulatedRandomLatency = Configuration.Instance.SimulatedRandomLatency; // config.SimulatedMinimumLatency = Configuration.Instance.SimulatedMinimumLatency; // config.SimulatedDuplicatesChance = Configuration.Instance.SimulatedDuplicatesChance; //} #endif //config.AutoFlushSendQueue = false; mNetPeer = new NetClient(config); mNetPeer.Start(); mDeliveryNotificationManager = new core.DeliveryNotificationManager(true, false); mReplicationManagerClient = new ReplicationManagerClient(); algo = new NetXorEncryption(GetClient(), "AceTopSecret"); mLastRoundTripTime = 0.0f; mTimeOfLastInputPacket = 0f; mServerAddress = inServerAddress; mState = NetworkClientState.SayingHello; mTimeOfLastHello = 0.0f; mTimeOfLastStartPlay = 0.0f; mName = inName; mWorldId = inWorldId; tryConnectCount = 0; mAvgRoundTripTime = new core.WeightedTimedMovingAverage(1.0f); NetOutgoingMessage hail = GetClient().CreateMessage("hail"); GetClient().Connect(mServerAddress, hail); IsTcp = false; IsUdpOk = false; IsTrySend = true; respawn = false; // tcp SetConnector(inServerAddress); LinkedObject.Clear(); }
public bool startServer() { mConnectionHealthThread = new Thread(new ThreadStart(connectionHealth)); mConnectionHealthThread.Name = "MapThread:Health"; //mConnectionHealthThread.Start(); mStaticActors = new StaticActors(STATIC_ACTORS_PATH); gamedataItems = Database.getItemGamedata(); Log.info(String.Format("Loaded {0} items.", gamedataItems.Count)); mWorldManager = new WorldManager(this); mWorldManager.LoadZoneList(); mWorldManager.LoadZoneEntranceList(); mWorldManager.LoadNPCs(); IPEndPoint serverEndPoint = new System.Net.IPEndPoint(IPAddress.Parse(ConfigConstants.OPTIONS_BINDIP), FFXIV_MAP_PORT); try { mServerSocket = new System.Net.Sockets.Socket(serverEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } catch (Exception e) { throw new ApplicationException("Could not create socket, check to make sure not duplicating port", e); } try { mServerSocket.Bind(serverEndPoint); mServerSocket.Listen(BACKLOG); } catch (Exception e) { throw new ApplicationException("Error occured while binding socket, check inner exception", e); } try { mServerSocket.BeginAccept(new AsyncCallback(acceptCallback), mServerSocket); } catch (Exception e) { throw new ApplicationException("Error occured starting listeners, check inner exception", e); } Console.Write("Game server has started @ "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("{0}:{1}", (mServerSocket.LocalEndPoint as IPEndPoint).Address, (mServerSocket.LocalEndPoint as IPEndPoint).Port); Console.ForegroundColor = ConsoleColor.Gray; mProcessor = new PacketProcessor(this, mConnectedPlayerList, mConnectionList); //mGameThread = new Thread(new ThreadStart(mProcessor.update)); //mGameThread.Start(); return(true); }
// // UDP送受信関連 // // UDP受信 private void buttonStart_Click(object sender, EventArgs e) { // // 実施中→終了 // if (udpClient_ != null) { udpClient_.Close(); udpClient_ = null; // ボタン等 change_ui(false); return; } // // 未実施→実施 // // 送信元 try { sourcePort_ = Int32.Parse(textBoxBindPort.Text); sourceIPAddress_ = IPAddress.Parse(comboBoxSourceIPs.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // 開始せず中断 } try { //UdpClientを作成し、指定したポート番号にバインドする System.Net.IPEndPoint localEP = new System.Net.IPEndPoint( System.Net.IPAddress.Any, //sourceIPAddress_, Int32.Parse(textBoxBindPort.Text) ); udpClient_ = new System.Net.Sockets.UdpClient(localEP); //非同期的なデータ受信を開始する udpClient_.BeginReceive(ReceiveCallback, udpClient_); // ボタン等 change_ui(true); } catch (Exception ex) { if (udpClient_ != null) { udpClient_.Close(); } udpClient_ = null; MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void CreateReceive(int setPort) { Debug.Log("CreateReceive 000"); myPort = setPort; //UdpClientを作成し、指定したポート番号にバインドする System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, myPort); udpClient = new System.Net.Sockets.UdpClient(localEP); //非同期的なデータ受信を開始する udpClient.BeginReceive(ReceiveCallback, udpClient); }
private void baseListen() { bool flag = true; while (this.isListening) { byte[] array = new byte[63488]; System.Net.EndPoint endPoint = null; try { endPoint = new System.Net.IPEndPoint(this.ipAddress, this.port); this.serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); this.serverSocket.Bind(endPoint); if (flag) { DebugCenter.GetInstance().clearStatusCode(DebugCenter.ST_TrapPortNA, true); flag = false; } this.serverSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveTimeout, 0); int num = this.serverSocket.ReceiveFrom(array, System.Net.Sockets.SocketFlags.None, ref endPoint); if (num > 0 && this.isListening) { string[] separator = new string[] { ":" }; string[] array2 = endPoint.ToString().Split(separator, System.StringSplitOptions.None); SocketMessager socketMessager = new SocketMessager(); socketMessager.Target = array2[0]; socketMessager.Port = System.Convert.ToInt32(array2[1]); socketMessager.DataLenth = num; socketMessager.DataBytes = array; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(this.waitCallback), socketMessager); } } catch (System.Exception) { try { System.Threading.Thread.Sleep(100); } catch (System.Exception) { } } finally { if (this.serverSocket != null) { this.serverSocket.Close(); } } } }
// Send a Frame to each registered BBMD except the original sender private void SendToBBMDs(byte[] buffer, int msg_length) { lock (BBMDs) { foreach (KeyValuePair <System.Net.IPEndPoint, System.Net.IPAddress> e in BBMDs) { System.Net.IPEndPoint endpoint = BBMDSentAdd(e.Key, e.Value); MyBBMDTransport.Send(buffer, msg_length, endpoint); } } }
static internal void ConnectToParticularEndpoint(ref bool connected, ref SocketException ex, ref Socket _peerSocket, string address, int port) { System.Net.IPEndPoint client_endpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(address), port); try { _peerSocket.Connect(client_endpoint); connected = true; } catch (SocketException e) { ex = e; } }
static void Receiver_Received2(System.Net.IPEndPoint client, byte[] data) { if (data != null && data.Length > 0) { Console.WriteLine("收到来自消费型客户端[" + client.ToString() + "]的数据共" + data.Length + "字节。"); } else { Console.WriteLine("收到来自消费型客户端[" + client.ToString() + "]的消息,无数据。"); } }
private void BeginListen() { try { System.Net.IPAddress address; if (string.IsNullOrEmpty(Host)) { if (Socket.OSSupportsIPv6 && Server.Options.UseIPv6) { address = IPAddress.IPv6Any; } else { address = IPAddress.Any; } } else { address = System.Net.IPAddress.Parse(Host); } IPEndPoint = new System.Net.IPEndPoint(address, Port); Socket = new Socket(IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (IPEndPoint.Address == IPAddress.IPv6Any) { Socket.DualMode = true; } if (this.ReuseAddress) { Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } Socket.Bind(IPEndPoint); Socket.Listen(512 * 4); if (Server.EnableLog(EventArgs.LogType.Info)) { Server.Log(EventArgs.LogType.Info, null, $"listen {Host}@{Port} success ssl:{SSL}"); } if (SyncAccept) { System.Threading.ThreadPool.QueueUserWorkItem((o) => OnSyncAccept()); } else { OnAsyncAccept(); } } catch (Exception e_) { Error = e_; if (Server.EnableLog(EventArgs.LogType.Error)) { Server.Log(EventArgs.LogType.Error, null, $"listen {Host}@{Port} error {e_.Message}|{e_.StackTrace}!"); } } }
public override void Connect(System.Net.IPEndPoint endPoint) { m_outSocketAsyncEventArgs.RemoteEndPoint = endPoint; if (!m_socket.ConnectAsync(m_outSocketAsyncEventArgs)) { CompletionStatus completionStatus = new CompletionStatus(this, m_state, OperationType.Connect, SocketError.Success, 0); m_completionPort.Queue(ref completionStatus); } }
private void IniLocalVideo(System.Net.IPEndPoint ServerEP) { if (AVC == null) { AVC = new IMLibrary.AV.Controls.AVComponent(); AVC.GetIPEndPoint += new IMLibrary.AV.Controls.AVComponent.GetIPEndPointEventHandler(AVC_GetIPEndPoint); AVC.TransmitConnected += new IMLibrary.AV.Controls.AVComponent.TransmitEventHandler(AVC_TransmitConnected); AVC.SetControls(panelLocalAV, panelRemotAV);// 绑定音视频控件 AVC.iniAV(IMLibrary.AV.VideoSizeModel.W320_H240, ServerEP); } }
private void Awake() { // 소켓을 생성합니다. m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(m_IPAdress); System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, kPort); singleton = this; //서버에 연결 요청을 합니다. m_Socket.Connect(remoteEndPoint); Debug.Log("Connecting"); }
void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe) { if (this.CheckAccess()) { textBox_Log.AppendText(DateTime.Now.ToString("hh:mm:ss") + "\t" + ipe.ToString() + "\t离线\n"); } else { this.Dispatcher.BeginInvoke(new CbDelegate <System.Net.IPEndPoint>(this.tcpServerEngine_ClientDisconnected), ipe); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { byte[] buf = System.Text.Encoding.ASCII.GetBytes(String.Format(Data, (random ? new Functions().RandomString() : null))); IPEndPoint RHost = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(IP), Port); while (IsFlooding) { Socket socket = null; if (Protocol == 1) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = true; try { socket.Connect(RHost); } catch { continue; } socket.Blocking = Resp; try { while (IsFlooding) { FloodCount++; socket.Send(buf); if (Delay >= 0) { System.Threading.Thread.Sleep(Delay + 1); } } } catch { } } if (Protocol == 2) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Blocking = Resp; try { while (IsFlooding) { FloodCount++; socket.SendTo(buf, SocketFlags.None, RHost); if (Delay >= 0) { System.Threading.Thread.Sleep(Delay + 1); } } } catch { } } } } catch { } }
private void ShowEvent(string msg, System.Net.IPEndPoint ipe) { var curResult = AppInfo.ClientInfoList.Where(p => p.IP == ipe.Address.ToString()); if (curResult == null || curResult.FirstOrDefault() == null) { return; } ClientInfo curIpDevInfo = null; if (this.InvokeRequired) { this.BeginInvoke(new CbDelegate <string, System.Net.IPEndPoint>(this.ShowEvent), msg, ipe); } else { if (msg == "上线") { var result = clientInfos.Where(p => p.IpPoint == ipe); if (result == null || result.FirstOrDefault() == null) { ClientInfo info = new ClientInfo(); info.IpPoint = ipe; info.State = 1; info.StateDes = "在线"; if (curResult != null) { info.Code = curResult.FirstOrDefault().Code; info.Name = curResult.FirstOrDefault().Name; } curIpDevInfo = info; clientInfos.Add(info); } else { result.FirstOrDefault().State = 1; result.FirstOrDefault().StateDes = "在线"; } } if (msg == "下线") { var result = clientInfos.Where(p => p.IpPoint == ipe); if (result != null && result.FirstOrDefault() != null) { result.FirstOrDefault().State = 0; result.FirstOrDefault().StateDes = "下线"; } curIpDevInfo = result.FirstOrDefault(); } } }
void Bvlc_MessageReceived(System.Net.IPEndPoint sender, BacnetBvlcFunctions function, BacnetBvlcResults result, object data) { if (!sender.Equals(BBMDep)) { return; // don't care } if (InvokeRequired) // GUI call back { BeginInvoke(new Action <System.Net.IPEndPoint, BacnetBvlcFunctions, BacnetBvlcResults, object>(Bvlc_MessageReceived), new object[] { sender, function, result, data }); return; } if (function == BacnetBvlcFunctions.BVLC_READ_BROADCAST_DIST_TABLE_ACK) // an table (could be empty) { List <Tuple <IPEndPoint, IPAddress> > Entries = (List <Tuple <IPEndPoint, IPAddress> >)data; BBMDTable.Rows.Clear(); foreach (Tuple <IPEndPoint, IPAddress> tpl in Entries) { BBMDTable.Rows.Add(new object[] { tpl.Item1.Address.ToString(), tpl.Item1.Port, tpl.Item2.ToString() }); } } if (function == BacnetBvlcFunctions.BVLC_READ_FOREIGN_DEVICE_TABLE_ACK) { List <Tuple <IPEndPoint, ushort, ushort> > Entries = (List <Tuple <IPEndPoint, ushort, ushort> >)data; FDRTable.Rows.Clear(); foreach (Tuple <IPEndPoint, ushort, ushort> tpl in Entries) { FDRTable.Rows.Add(new object[] { tpl.Item1.ToString(), tpl.Item2.ToString(), tpl.Item3.ToString() }); } } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_SUCCESSFUL_COMPLETION) && (WriteInOperation)) { WriteInOperation = false; transport.Bvlc.SendReadBroadCastTable(BBMDep); } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_READ_BROADCAST_DISTRIBUTION_TABLE_NAK)) { lbBBMDlInfo.Visible = true; lbBBMDlInfo.Text = "Read Broadcast Table Rejected"; } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_WRITE_BROADCAST_DISTRIBUTION_TABLE_NAK) && (WriteInOperation)) { lbBBMDlInfo.Visible = true; lbBBMDlInfo.Text = "Write Broadcast Table Rejected"; } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_READ_FOREIGN_DEVICE_TABLE_NAK)) { ldlFDRInfo.Visible = true; ldlFDRInfo.Text = "Read FDR Table Rejected"; } }
/// <summary> /// 初始化音视频通信组件 /// </summary> /// <param name="Model">视频显示大小模式</param> public void iniAV(VideoSizeModel Model, System.Net.IPEndPoint ServerEP) { if (!IsIni) { IsIni = true;//标识已经初始化 } else { return; //如果已经初始化,则退出 } VideoSize.SetModel(Model); //设置视频编码尺寸 if (cam == null) { iniVideoCapturer(); } #region //创建新的视频捕捉组件 //if (VC == null) //{ // VC = new VideoCapturer(this.cLocal); // VC.VideoCapturerBefore += new VideoCapturer.VideoCaptureredEventHandler(VC_VideoCapturerBefore); // VC.VideoDataCapturered += new VideoCapturer.VideoCaptureredEventHandler(VC_VideoDataCapturered); // VC.StartVideoCapture(Model);//开始捕捉视频 //} #endregion if (AE == null) { AE = new AudioEncoder();//创建G711音频编解码器 } if (AC == null) { AC = new AudioCapturer(this.trackBarOut, this.trackBarIn);//创建新的音频捕捉组件 AC.AudioDataCapturered += new AudioCapturer.AudioDataCaptureredEventHandler(AC_AudioDataCapturered); } if (AR == null) { AR = new AudioRender();//创建G711音频回放组件 } if (frameTransmit == null) { frameTransmit = new FrameTransmit(ServerEP); frameTransmit.GetIPEndPoint += new FrameTransmit.GetIPEndPointEventHandler(frameTransmit_GetIPEndPoint); frameTransmit.RecAudioData += new FrameTransmit.RecDataEventHandler(frameTransmit_RecAudioData); frameTransmit.RecVideoData += new FrameTransmit.RecDataEventHandler(frameTransmit_RecVideoData); frameTransmit.TransmitConnected += new FrameTransmit.TransmitEventHandler(frameTransmit_TransmitConnected); frameTransmit.Start(); } }
internal static void CopyEndpoint(NetEndPoint src, NetEndPoint dst) { dst.Port = src.Port; if (src.AddressFamily == AddressFamily.InterNetwork) { dst.Address = src.Address.MapToIPv6(); } else { dst.Address = src.Address; } }
public Server GetAServer(IStrategyCallerType type, System.Net.IPEndPoint localIPEndPoint, EndPoint destEndPoint) { if (type == IStrategyCallerType.TCP) { ChooseNewServer(); } if (_currentServer == null) { return(null); } return(_currentServer.server); }
// UDP/IP受信コールバック関数 public void ReceiveCallback(IAsyncResult AR) { // UDP/IP受信 System.Net.IPEndPoint ipAny = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); Byte[] rdat = ((System.Net.Sockets.UdpClient)AR.AsyncState).EndReceive(AR, ref ipAny); String rstr = System.Text.Encoding.GetEncoding("SHIFT-JIS").GetString(rdat); //WriteLine(rstr); // 連続で(複数回)データ受信する為の再設定 ((System.Net.Sockets.UdpClient)AR.AsyncState).BeginReceive(ReceiveCallback, AR.AsyncState); }
void ur_Received(UdpRevicer self, System.Net.IPEndPoint arg2, byte[] data) { if (!_isPlay) { return; } ur.beginReceive(); RTPModel pkg = new RTPModel(data); queue.Enqueue(FrameHelper.getFrame(pkg.payload)); recvFrameed.Invoke(this, pkg.SequenceNumber, pkg.TimeStamp); }
private void BeginReceiveTask(string comPort) { Task.Run(() => { System.Net.IPEndPoint connectIP = new System.Net.IPEndPoint( IPAddress.Any, int.Parse(comPort)); UdpClient = new System.Net.Sockets.UdpClient(connectIP); UdpClient.BeginReceive(Receive, UdpClient); }); }
// Use this for initialization void Start() { String strHostName = string.Empty; strHostName = System.Net.Dns.GetHostName(); System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName); _addresses = ipEntry.AddressList; _ipAddress = _addresses [2]; _ipLocalEndPoint = new System.Net.IPEndPoint(_ipAddress, 800); this.Start(800); }