static void Main() { Console.WriteLine("SIPSorcery sip.js Demo"); Log = AddConsoleLogger(); var sipTransport = new SIPTransport(); EnableTraceLogs(sipTransport); var sipChannel = new SIPWebSocketChannel(IPAddress.Loopback, 8081); sipTransport.AddSIPChannel(sipChannel); var userAgent = new SIPUserAgent(sipTransport, null, true); userAgent.OnIncomingCall += async(ua, req) => { Log.LogDebug($"Auto-answering incoming call from {req.Header.From}."); var uas = userAgent.AcceptCall(req); var peerConnection = new RTCPeerConnection(null); peerConnection.onconnectionstatechange += (state) => { Log.LogDebug($"Peer connection state change to {state}."); if (state == RTCPeerConnectionState.failed) { peerConnection.Close("ice disconnection"); } else if (state == RTCPeerConnectionState.connected) { peerConnection.OnRtpPacketReceived += OnRtpPacketReceived; } else if (state == RTCPeerConnectionState.closed) { peerConnection.OnRtpPacketReceived -= OnRtpPacketReceived; } }; MediaStreamTrack audioTrack = new MediaStreamTrack(new List <AudioFormat> { new AudioFormat(SDPWellKnownMediaFormatsEnum.PCMU) }, MediaStreamStatusEnum.SendRecv); peerConnection.addTrack(audioTrack); //MediaStreamTrack videoTrack = new MediaStreamTrack("1", SDPMediaTypesEnum.video, false, new List<SDPMediaFormat> { new SDPMediaFormat(SDPMediaFormatsEnum.VP8) }, MediaStreamStatusEnum.Inactive); //peerConnection.addTrack(videoTrack); var answerResult = await userAgent.Answer(uas, peerConnection); }; Console.Write("press any key to exit..."); Console.Read(); sipTransport.Shutdown(); }
public async void WebSocketLoopbackLargeSendReceiveTest() { logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name); var serverChannel = new SIPWebSocketChannel(IPAddress.Loopback, 9001); var clientChannel = new SIPClientWebSocketChannel(); var sipTransport = new SIPTransport(); sipTransport.AddSIPChannel(new List <SIPChannel> { serverChannel, clientChannel }); ManualResetEvent gotResponseMre = new ManualResetEvent(false); SIPRequest receivedRequest = null; SIPResponse receivedResponse = null; sipTransport.SIPTransportRequestReceived += (localSIPEndPoint, remoteEndPoint, sipRequest) => { receivedRequest = sipRequest; SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); optionsResponse.Header.UnknownHeaders.Add($"X-Response-Random:{Crypto.GetRandomString(1000)}"); optionsResponse.Header.UnknownHeaders.Add("X-Response-Final: TheEnd"); return(sipTransport.SendResponseAsync(optionsResponse)); }; sipTransport.SIPTransportResponseReceived += (localSIPEndPoint, remoteEndPoint, sipResponse) => { receivedResponse = sipResponse; gotResponseMre.Set(); return(Task.CompletedTask); }; var serverUri = serverChannel.GetContactURI(SIPSchemesEnum.sip, clientChannel.ListeningSIPEndPoint); var optionsRequest = SIPRequest.GetRequest(SIPMethodsEnum.OPTIONS, serverUri); optionsRequest.Header.UnknownHeaders.Add($"X-Request-Random:{Crypto.GetRandomString(1000)}"); optionsRequest.Header.UnknownHeaders.Add("X-Request-Final: TheEnd"); await sipTransport.SendRequestAsync(optionsRequest); gotResponseMre.WaitOne(TRANSPORT_TEST_TIMEOUT, false); Assert.NotNull(receivedRequest); Assert.NotNull(receivedResponse); //rj2: confirm that we have received the whole SIP-Message by checking for the last x-header (issue #175, websocket fragmented send/receive) Assert.Contains("X-Request-Final: TheEnd", receivedRequest.Header.UnknownHeaders); Assert.Contains("X-Response-Final: TheEnd", receivedResponse.Header.UnknownHeaders); sipTransport.Shutdown(); logger.LogDebug("Test complete."); }
public async void WebSocketLoopbackSendReceiveTest() { logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name); var serverChannel = new SIPWebSocketChannel(IPAddress.Loopback, 9000); var clientChannel = new SIPClientWebSocketChannel(); var sipTransport = new SIPTransport(); sipTransport.AddSIPChannel(new List <SIPChannel> { serverChannel, clientChannel }); ManualResetEvent gotResponseMre = new ManualResetEvent(false); sipTransport.SIPTransportRequestReceived += (localSIPEndPoint, remoteEndPoint, sipRequest) => { SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); return(sipTransport.SendResponseAsync(optionsResponse)); }; SIPResponse rtnResponse = null; sipTransport.SIPTransportResponseReceived += (localSIPEndPoint, remoteEndPoint, sipResponse) => { rtnResponse = sipResponse; gotResponseMre.Set(); return(Task.CompletedTask); }; var serverUri = serverChannel.GetContactURI(SIPSchemesEnum.sip, clientChannel.ListeningSIPEndPoint); var optionsRequest = SIPRequest.GetRequest(SIPMethodsEnum.OPTIONS, serverUri); await sipTransport.SendRequestAsync(optionsRequest); gotResponseMre.WaitOne(TRANSPORT_TEST_TIMEOUT, false); Assert.NotNull(rtnResponse); sipTransport.Shutdown(); logger.LogDebug("Test complete."); }
static void Main() { Console.WriteLine("SIPSorcery Getting Started Demo"); var sipTransport = new SIPTransport(); EnableTraceLogs(sipTransport); var sipChannel = new SIPWebSocketChannel(IPAddress.Loopback, 80); var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("localhost.pfx"); var sipChannelSecure = new SIPWebSocketChannel(IPAddress.Loopback, 443, wssCertificate); sipTransport.AddSIPChannel(sipChannel); sipTransport.AddSIPChannel(sipChannelSecure); sipTransport.SIPTransportRequestReceived += async(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) => { Console.WriteLine($"Request received {localSIPEndPoint}<-{remoteEndPoint}: {sipRequest.StatusLine}"); if (sipRequest.Method == SIPMethodsEnum.OPTIONS | sipRequest.Method == SIPMethodsEnum.MESSAGE) { SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); await sipTransport.SendResponseAsync(okResponse); } else if (sipRequest.Method == SIPMethodsEnum.REGISTER) { SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); okResponse.Header.Contact = sipRequest.Header.Contact; await sipTransport.SendResponseAsync(okResponse); } }; Console.Write("press any key to exit..."); Console.Read(); sipTransport.Shutdown(); }
static async Task Main() { Console.WriteLine("SIPSorcery sip.js Demo"); AddConsoleLogger(); var sipTransport = new SIPTransport(); EnableTraceLogs(sipTransport); var sipChannel = new SIPWebSocketChannel(IPAddress.Loopback, 80); var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("localhost.pfx"); var sipChannelSecure = new SIPWebSocketChannel(IPAddress.Loopback, 443, wssCertificate); sipTransport.AddSIPChannel(sipChannel); sipTransport.AddSIPChannel(sipChannelSecure); var userAgent = new SIPUserAgent(sipTransport, null, true); userAgent.OnIncomingCall += async(ua, req) => { Log.LogDebug($"Auto-answering incoming call from {req.Header.From}."); var uas = userAgent.AcceptCall(req); RTCConfiguration pcConfiguration = new RTCConfiguration { certificates = new List <RTCCertificate> { new RTCCertificate { X_CertificatePath = DTLS_CERTIFICATE_PATH, X_KeyPath = DTLS_KEY_PATH, X_Fingerprint = DTLS_CERTIFICATE_FINGERPRINT } }, //X_RemoteSignallingAddress = context.UserEndPoint.Address, //iceServers = new List<RTCIceServer> { new RTCIceServer { urls = SIPSORCERY_STUN_SERVER } } }; var peerConnection = new RTCPeerConnection(pcConfiguration); var dtls = new DtlsHandshake(DTLS_CERTIFICATE_PATH, DTLS_KEY_PATH); peerConnection.OnTimeout += (mediaType) => { peerConnection.Close("remote timeout"); }; peerConnection.oniceconnectionstatechange += async(state) => { Log.LogDebug($"ICE connection state change to {state}."); if (state == RTCIceConnectionState.connected) { var remoteEndPoint = peerConnection.AudioDestinationEndPoint; Log.LogInformation($"ICE connected to remote end point {remoteEndPoint}."); await Task.Run(() => DoDtlsHandshake(peerConnection, dtls)) .ContinueWith((dtlsResult) => { Log.LogDebug($"dtls handshake result {dtlsResult.Result}."); if (dtlsResult.Result) { var remoteEP = peerConnection.AudioDestinationEndPoint; peerConnection.SetDestination(SDPMediaTypesEnum.audio, remoteEP, remoteEP); } else { dtls.Shutdown(); peerConnection.Close("dtls handshake failed."); } }); } }; peerConnection.onconnectionstatechange += (state) => { if (state == RTCPeerConnectionState.connected) { var remoteEP = peerConnection.AudioDestinationEndPoint; Log.LogDebug($"DTLS connected on {remoteEP}."); peerConnection.SetDestination(SDPMediaTypesEnum.audio, remoteEP, remoteEP); peerConnection.SetDestination(SDPMediaTypesEnum.video, remoteEP, remoteEP); peerConnection.OnReceiveReport += RtpSession_OnReceiveReport; peerConnection.OnSendReport += RtpSession_OnSendReport; // peerConnection.OnRtpPacketReceived += OnRtpPacketReceived; } }; MediaStreamTrack audioTrack = new MediaStreamTrack(SDPMediaTypesEnum.audio, false, new List <SDPMediaFormat> { new SDPMediaFormat(SDPMediaFormatsEnum.PCMU) }, MediaStreamStatusEnum.SendRecv); peerConnection.addTrack(audioTrack); //MediaStreamTrack videoTrack = new MediaStreamTrack("1", SDPMediaTypesEnum.video, false, new List<SDPMediaFormat> { new SDPMediaFormat(SDPMediaFormatsEnum.VP8) }, MediaStreamStatusEnum.Inactive); //peerConnection.addTrack(videoTrack); var answerResult = await userAgent.Answer(uas, peerConnection); }; Console.Write("press any key to exit..."); Console.Read(); sipTransport.Shutdown(); }
/// <summary> /// Executes the command set by the program's command line arguments. /// </summary> /// <param name="options">The options that dictate the SIP command to execute.</param> static async Task RunCommand(Options options) { try { logger.LogDebug($"RunCommand {options.Destination}"); (var dstEp, var dstUri) = ParseDestination(options.Destination); logger.LogDebug($"Destination IP end point {dstEp} and SIP URI {dstUri}"); int sendCount = 0; bool success = true; do { IPAddress localAddress = (dstEp.Address.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6Any : IPAddress.Any; SIPChannel sipChannel = null; switch (dstEp.Protocol) { case SIPProtocolsEnum.tcp: sipChannel = new SIPTCPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT)); (sipChannel as SIPTCPChannel).DisableLocalTCPSocketsCheck = true; // Allow sends to listeners on this host. break; case SIPProtocolsEnum.tls: var certificate = new X509Certificate2(@"localhost.pfx", ""); sipChannel = new SIPTLSChannel(certificate, new IPEndPoint(localAddress, DEFAULT_SIPS_CLIENT_PORT)); break; case SIPProtocolsEnum.udp: sipChannel = new SIPUDPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT)); break; case SIPProtocolsEnum.ws: sipChannel = new SIPWebSocketChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT), null); break; case SIPProtocolsEnum.wss: var wsCertificate = new X509Certificate2(@"localhost.pfx", ""); sipChannel = new SIPWebSocketChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT), wsCertificate); break; default: throw new ApplicationException($"Don't know how to create SIP channel for transport {dstEp.Protocol}."); } SIPTransport sipTransport = new SIPTransport(); sipTransport.AddSIPChannel(sipChannel); if (sendCount > 0 && options.Period > 0) { await Task.Delay(options.Period * 1000); } sendCount++; DateTime sendTime = DateTime.Now; var sendTask = SendOptionsTaskAsync(sipTransport, dstUri); var result = await Task.WhenAny(sendTask, Task.Delay(options.Timeout * 1000)); TimeSpan duration = DateTime.Now.Subtract(sendTime); if (!sendTask.IsCompleted) { logger.LogWarning($"=> Request to {dstEp} did not get a response on send {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms."); success = false; } else if (!sendTask.Result) { logger.LogWarning($"=> Request to {dstEp} did not get the expected response on request {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms."); success = false; } else { logger.LogInformation($"=> Got correct response on send {sendCount} of {options.Count} in {duration.TotalMilliseconds.ToString("0")}ms."); } logger.LogDebug("Shutting down the SIP transport..."); sipTransport.Shutdown(); if (success == false) { break; } }while (sendCount < options.Count); DNSManager.Stop(); // Give the transport half a second to shutdown (puts the log messages in a better sequence). await Task.Delay(500); logger.LogInformation($"=> Command completed {((success) ? "successfully" : "with failure")}."); } catch (Exception excp) { logger.LogError($"Exception RunCommand. {excp.Message}"); } }