I write program using SuperWebsocket i Library , but my connections more than 100 connections result message is : Max connection number 100 was reached ! how can i increase number of connections ?
I didn't test it, but the WebSocketServer class has a Config property.
It is of type IServerConfig, which has a property MaxConnectionNumber.
(The default value is 100).
The WebSocketServer class has a method Setup, which takes an IServerConfig as parameter.
The following code shows how to change MaxConnectionNumber.
class Program
{
protected static WebSocketServer wsServer { get; private set; }
static void Main(string[] args)
{
wsServer = new WebSocketServer();
var config = new ServerConfig();
config.Port = 8088;
config.Ip = "Any";
config.Mode = SocketMode.Tcp;
config.MaxConnectionNumber = 1000;
config.Name = "ChatServer";
config.ReceiveBufferSize = 16384;
config.SendBufferSize = 1024;
var rootConfig = new RootConfig() { };
var ret = wsServer.Setup(rootConfig, config, null, null, new ConsoleLogFactory(), null, null);
if (!ret)
{
throw new Exception("Server is not setup correctly");
}
else
{
wsServer.NewSessionConnected += wsServer_NewSessionConnected;
wsServer.NewMessageReceived += wsServer_NewMessageReceived;
wsServer.NewDataReceived += wsServer_NewDataReceived;
wsServer.SessionClosed += wsServer_SessionClosed;
wsServer.Start();
int maxConn = wsServer.Config.MaxConnectionNumber;
Console.WriteLine("Server is running on port " + config.Port + ". Max Connection is " + maxConn.ToString() + ". Press Enter to exit...");
Console.ReadKey();
wsServer.Stop();
}
}
static void wsServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine("NewSessionConnected");
}
static void wsServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Console.WriteLine("sessionClosed");
}
static void wsServer_NewDataReceived(WebSocketSession session, byte[] value)
{
Console.WriteLine("NewDataReceived");
}
static void wsServer_NewMessageReceived(WebSocketSession session, string value)
{
Console.WriteLine("NewMessageReceived: " + value);
}
}
Related
Today I encountered a problem. When I use cmd application , create thread with Task.Factory than my Task live only 30 minutes. I tried create with nssm - background service in windows. But this service work only 30 minutes. I solved this problem, when use main thread and synchronic programming. But I don't have idea for what my task live only === 30 minutes. I think GC, but ....
For example code:
Task.Factory.StartNew(() =>
{
string Milliseconds = builder.Configuration["DefaultParams:CheckingTime"];
try
{
var hetmanClient = Hetman.Instance;
int MS = Int32.Parse(Milliseconds);
Timer aTimer = new Timer((object? o) =>
{
CheckNewFileInFolder(app.Environment);
}, null, 0, MS);
}
catch
{
PrintToFile.PrintToFileAndConsole("Wrong number in params: DefaultParams:CheckingTime");
}
})
void CheckNewFileInFolder(IWebHostEnvironment appEnvironment)
{
PrintToFile.PrintToFileAndConsole($"Checking new record in folder");
string path = appEnvironment.WebRootPath + #"\ReceivedXMLs";
string[] NewFiles = Directory.GetFiles(path);
foreach(var i in NewFiles)
{
string NextPath = appEnvironment.WebRootPath + #"\AddedToDBXMLs" + i.Replace(path, "");
string text = File.ReadAllText(i);
try
{
string queryString = $"JUST SQL";
PrintToFile.PrintToFileAndConsole(queryString);
OdbcCommand command = new OdbcCommand(queryString, instance.conn);
int result = command.ExecuteNonQuery();
PrintToFile.PrintToFileAndConsole("Result code from database: " + result);
File.Move(i, NextPath);
}
catch(Exception ex)
{
PrintToFile.PrintToFileAndConsole("ERROR: " + ex.Message);
}
}
}
public class PrintToFile
{
private static PrintToFile instance = null;
private PrintToFile() {}
public static PrintToFile Instance
{
get
{
if (instance == null)
{
instance = new PrintToFile();
}
return instance;
}
}
private static readonly object _lock = new object();
public static string path = string.Empty;
public void Create(IWebHostEnvironment appEnvironment)
{
path = appEnvironment.WebRootPath + #"\Logging\Log.txt";
}
public static void PrintToFileAndConsole(string text)
{
lock (_lock)
{
Console.WriteLine(DateTime.Now + " : " + text);
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine(DateTime.Now + " : " + text);
}
}
}
}
Answer Why my task lived only 30 minutes
My problem is, it all works when transmitter and Subscribe are connected. All messages are transmitted correctly.
But if I disconnect the connection, so the Subscribe is no longer connected and then reconnect.
I get all the messages in between but the last one
Double.
The double received is wrong. Why is it like that ?
And how can I solve this?
Publisher
public class Programm
{
static MqttClient mqttClient;
static async Task Main(string[] args)
{
var locahlost = true;
var clientName = "Sender 1";
Console.WriteLine($"{clientName} Startet");
var servr = locahlost ? "localhost" : "test.mosquitto.org";
mqttClient = new MqttClient(servr);
mqttClient.Connect(clientName, null, null, false, 60);
Task.Run(() =>
{
if (mqttClient != null && mqttClient.IsConnected)
{
for (int i = 0; i < 100; i++)
{
var Message = $"{clientName} ->Test {i}";
mqttClient.Publish("Application1/NEW_Message", Encoding.UTF8.GetBytes($"{Message}"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
Console.WriteLine(Message);
Thread.Sleep(i * 1000);
}
}
});
Console.WriteLine($"{clientName} End");
}
}
subscriber
public class Programm
{
static MqttClient mqttClient;
static async Task Main(string[] args)
{
var clientName = "subscriber 1";
var locahlost = true;
Console.WriteLine($"Start of {clientName}");
Task.Run(() =>
{
var servr = locahlost ? "localhost" : "test.mosquitto.org";
mqttClient = new MqttClient(servr);
mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
mqttClient.Subscribe(new string[] { "Application1/NEW_Message" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
mqttClient.Connect(clientName, null, null, false, 60);
//mqttClient.Connect(clientName);
});
// client.UseConnecedHandler(e=> {Console.WriteLine("Verbunden") });
Console.ReadLine();
Console.WriteLine($"end of {clientName}");
Console.ReadLine();
}
private static void MqttClient_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
var message = Encoding.UTF8.GetString(e.Message);
Console.WriteLine(message);
}
}
server
static async Task Main(string[] args)
{
Console.WriteLine("Server");
MqttServerOptionsBuilder options = new MqttServerOptionsBuilder()
// set endpoint to localhost
.WithDefaultEndpoint()
// port used will be 707
.WithDefaultEndpointPort(1883)
// handler for new messages
.WithConnectionValidator(OnNewConnection)
.WithApplicationMessageInterceptor(OnNewMessage)
.WithClientMessageQueueInterceptor(OnOut)
.WithDefaultCommunicationTimeout(TimeSpan.FromMinutes(5))
.WithMaxPendingMessagesPerClient(10)
.WithPersistentSessions()
.WithStorage(storage)
;
// creates a new mqtt server
IMqttServer mqttServer = new MqttFactory().CreateMqttServer();
// start the server with options
mqttServer.StartAsync(options.Build()).GetAwaiter().GetResult();
// keep application running until user press a key
Console.ReadLine();
}
private static void OnOut(MqttClientMessageQueueInterceptorContext context)
{
var payload = context.ApplicationMessage?.Payload == null ? null : Encoding.UTF8.GetString(context.ApplicationMessage?.Payload);
Out_MessageCounter++;
var messageValue = Encoding.UTF8.GetString(context?.ApplicationMessage?.Payload);
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("Messsage OUT :->");
Console.WriteLine($"MessageId: {Out_MessageCounter} - TimeStamp: {DateTime.Now} -- Message: ClientId = {context.ReceiverClientId}, Topic = {context.ApplicationMessage?.Topic}, Payload = {payload}, QoS = {context.ApplicationMessage?.QualityOfServiceLevel}, Retain-Flag = {context.ApplicationMessage?.Retain} Message {messageValue}");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
public static void OnNewConnection(MqttConnectionValidatorContext context)
{
Console.WriteLine(
$"New connection: ClientId = {context.ClientId}, Endpoint = {context.Endpoint}");
}
public static void OnNewMessage(MqttApplicationMessageInterceptorContext context)
{
var payload = context.ApplicationMessage?.Payload == null ? null : Encoding.UTF8.GetString(context.ApplicationMessage?.Payload);
In_MessageCounter++;
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("Messsage IN :->");
Console.WriteLine($"MessageId: {In_MessageCounter} - TimeStamp: {DateTime.Now} -- Message: ClientId = {context.ClientId}, Topic = {context.ApplicationMessage?.Topic}, Payload = {payload}, QoS = {context.ApplicationMessage?.QualityOfServiceLevel}, Retain-Flag = {context.ApplicationMessage?.Retain} Message {Encoding.UTF8.GetString(context?.ApplicationMessage?.Payload)}");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
From the source:
/// Publish a message asynchronously
/// <param name="topic">Message topic</param>
/// <param name="message">Message data (payload)</param>
/// <param name="qosLevel">QoS Level</param>
/// <param name="retain">Retain flag</param>
/// <returns>Message Id related to PUBLISH message</returns>
public ushort Publish(string topic, byte[] message, byte qosLevel, bool retain)
You probably want to set the last value to false
mqttClient.Publish("Application1/NEW_Message", Encoding.UTF8.GetBytes($"{Message}"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
For more details about retained messages see here:
https://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages/
I have a program that needs to scan for other devices running my program on the network. The solution I came up with was to call each ipAddress to see if my program is running.
The code below is completely blocking the cpu:-
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FileWire
{
class SearchNearby
{
private bool pc_search_cancelled = false;
private SynchronizedCollection<Thread> PCSearchThreadList;
private ConcurrentDictionary<String, String> NearbyPCList;
public void NewPcFound(string s, string s1)
{
Console.WriteLine(string.Format("PC Found at: {0} PC Name: {1}", s, s1));
}
public SearchNearby()
{
startPCScan();
while (true)
{
bool isAnyAlive = false;
foreach(Thread t in PCSearchThreadList)
{
isAnyAlive |= t.IsAlive;
}
if (!isAnyAlive)
{
Console.WriteLine("Search Complete");
foreach (var a in NearbyPCList)
{
Console.WriteLine(a.Key + " ;; " + a.Value);
}
startPCScan();
}
Thread.Sleep(100);
}
}
private void startPCScan()
{
PCSearchThreadList = new SynchronizedCollection<Thread>();
NearbyPCList = new ConcurrentDictionary<String, String>();
pc_search_cancelled = false;
String add = "";
System.Net.IPAddress[] ad = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList;
foreach (System.Net.IPAddress ip in ad)
{
add += ip.ToString() + "\n";
}
bool connected;
if (add.Trim(' ').Length == 0)
{
connected = false;
}
else
{
connected = true;
}
if (connected)
{
try
{
String[] addresses = add.Split('\n');
foreach (String address in addresses)
{
int myIP = int.Parse(address.Substring(address.LastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++)
{
int finalDef = def;
for (int j = 0; j < 10; j++)
{
string finalJ = j.ToString();
Thread thread = new Thread(new ThreadStart(() =>
{
if (!pc_search_cancelled)
{
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++)
{
if (!pc_search_cancelled)
{
if (i != myIP)
{
String callToAddress = "http://" + address.Substring(0, address.LastIndexOf(".")) + "." + i + ":" + (1234 + int.Parse(finalJ)).ToString();
String name = canGetNameAndAvatar(callToAddress);
if (name != null)
{
NearbyPCList[callToAddress] = name;
NewPcFound(callToAddress, name);
}
}
}
}
}
}));
PCSearchThreadList.Add(thread);
thread.Start();
}
}
}
} catch (Exception e) {
}
}
}
private String canGetNameAndAvatar(String connection)
{
String link = connection + "/getAvatarAndName";
link = link.Replace(" ", "%20");
try
{
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(500);
var a = new Task<HttpResponseMessage>[1];
a[0] = client.GetAsync(link);
Task.WaitAll(a);
var b = a[0].Result.Content.ReadAsStringAsync();
Task.WaitAll(b);
Console.WriteLine(b.Result);
string result = b.Result;
result = result.Substring(result.IndexOf("<body>") + 6, result.IndexOf("</body>") - (result.IndexOf("<body>") + 6));
AvtarAndName json = JsonConvert.DeserializeObject<AvtarAndName>(result);
if (json != null)
{
return json.name;
}
}
catch
{
return null;
}
return null;
}
}
}
This is the exact C# version of the java code I was using in Java:-
import com.sun.istack.internal.Nullable;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class PCScan {
private static boolean pc_search_cancelled = false;
private static List<Thread> PCSearchThreadList;
private static HashMapWithListener<String, String> NearbyPCList;
public static void main(String[] args) {
start();
while (true) {
int numCompleted = 0;
for (Thread t : PCSearchThreadList) {
if (!t.isAlive()) {
numCompleted++;
}
}
if (numCompleted == PCSearchThreadList.size()) {
start();
}
}
}
private static void start() {
try {
startPCScan();
} catch (SocketException e) {
e.printStackTrace();
}
NearbyPCList.setPutListener(new HashMapWithListener.putListener() {
#Override
public void onPut(Object key, Object value) {
System.out.println(key.toString() + ";;" + value.toString());
}
});
}
private static void startPCScan() throws SocketException {
pc_search_cancelled = false;
PCSearchThreadList = new CopyOnWriteArrayList<>();
NearbyPCList = new HashMapWithListener<>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
boolean connected;
String add = "";
while (enumeration.hasMoreElements()) {
NetworkInterface interfacea = enumeration.nextElement();
if (!interfacea.isLoopback()) {
Enumeration<InetAddress> enumeration1 = interfacea.getInetAddresses();
while (enumeration1.hasMoreElements()) {
String address = enumeration1.nextElement().getHostAddress();
if (address.split("\\.").length == 4) {
add += address + "\n";
}
}
}
}
System.out.println(add);
connected = true;
if (connected) {
try {
String[] addresses = add.split("\n");
addresses = new HashSet<String>(Arrays.asList(addresses)).toArray(new String[0]);
for (String address : addresses) {
int myIP = Integer.parseInt(address.substring(address.lastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++) {
int finalDef = def;
for (int j = 0; j < 10; j++) {
int finalJ = j;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
if (!pc_search_cancelled) {
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++) {
if (!pc_search_cancelled) {
if (i != myIP) {
String callToAddress = "http://" + address.substring(0, address.lastIndexOf(".")) + "." + i + ":" + String.valueOf(Integer.parseInt("1234") + finalJ);
String name = canGetNameAndAvatar(callToAddress);
if (name != null) {
NearbyPCList.put(callToAddress, name);
}
}
}
}
}
}
});
PCSearchThreadList.add(thread);
thread.start();
}
}
// }
// }).start();
}
} catch (Exception e) {
}
}
}
private static String canGetNameAndAvatar(String connection) {
String link = connection + "/getAvatarAndName";
link = link.replaceAll(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
httpParams.setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
String result = sb.toString();
result = result.substring(result.indexOf("<body>") + 6, result.indexOf("</body>"));
JSONObject json = new JSONObject(result);
if (json != null) {
return json.getString("name");
}
}
catch (Exception ignored){
return null;
}
return null;
}
static class HashMapWithListener<K, V> extends HashMap<K, V> {
private putListener PutListener;
public void setPutListener(putListener PutListener) {
this.PutListener = PutListener;
}
#Nullable
#Override
public V put(K key, V value) {
PutListener.onPut(key, value);
return super.put(key, value);
}
interface putListener {
public void onPut(Object key, Object value);
}
}
}
The java code runs absolutely fine and only uses about 20 percent cpu while c# code absolutely locks the PC. I tried Webclient, webrequest, httpClient. All have literally the same performance.
I need the code to be in c# as I can't include whole JRE in my program since it is too large. The rest of my program and GUI is in WPF format.
Also, I need the code to take a maximum of 50seconds while scanning ports 1234-1243. This code also works absolutely fine even on a midrange android phone. So, I don't know what the problem is.
I would suggest something like this (I've simplified it for the sake of an example):
private static HttpClient _client = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(500) };
private async Task<Something> GetSomething(string url)
{
using (HttpResponseMessage response = await _client.GetAsync(url))
{
string json = await response.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Something>(json);
}
}
private async Task<Something[]> GetSomethings(string[] urls)
{
IEnumerable<Task<Something>> requestTasks = urls.Select(u => GetSomething(u));
Something[] results = await Task.WhenAll<Something>(requestTasks);
return results;
}
You should also make the method calling GetSomethings async, and await it, and do the same all the way up the call chain.
async/await uses a thread pool to execute, and the thread is actually suspended while the IO part of the request occurs, meaning that no CPU time is used during this period. When then IO part is done, it resumes the code at the await.
Related information:
Asynchronous programming documentation
How and when to use 'async' and 'await'
You are using threads and multithreading completely wrong.
Because I cannot really understand what you are trying to do because everything is cramped into one function, I cannot provide you with a more detailed solution.
But let me suggest the following: I understand, you want to execute some operation in the background connecting to some other computer, try something like this
var taskList = new List<Task>();
foreach (var pc in computers)
{
var currentPcTask = Task.Run(() => DoYourWorkForSomePcHere(pc));
taskList.Add(currentPcTask);
}
Task.WaitAll(taskList.ToArray());
This will be very CPU efficient.
I am trying to send a predefined message to our SIP phones which will trigger an event(reboot) in C#. I found some scripts in other languages (perl/python) which do exactly what i am trying to do but have never done this before. I have most of if ported over but really don't know if i have all of right elements. Here is script i am trying to port:
#!/usr/bin/perl -w
use Net::Ping;
use Socket;
my $phone_ip = $ARGV[0];
sub reboot_sip_phone { # Send the phone a check-sync to reboot it
$local_ip = $phone_ip;
$sip_to = $phone_ip;
$sip_from = "0";
$tm = time();
$call_id = $tm . "msgto$sip_to";
$httptime = `date -R`;
$MESG = "NOTIFY sip:$sip_to\#$phone_ip:5060 SIP/2.0
Via: SIP/2.0/UDP $local_ip
From: <sip:$sip_from\#$local_ip>
To: <sip:$sip_to\#$phone_ip>
Event: check-sync
Date: $httptime
Call-ID: $call_id\#$local_ip
CSeq: 1300 NOTIFY
Contact: <sip:$sip_from\#$local_ip>
Content-Length: 0 ";
$proto = getprotobyname('udp');
socket( SOCKET, PF_INET, SOCK_DGRAM, $proto );
$iaddr = inet_aton("$phone_ip");
$paddr = sockaddr_in( 5060, $iaddr );
bind( SOCKET, $paddr );
$port = 5060;
$hisiaddr = inet_aton($phone_ip);
$hispaddr = sockaddr_in( $port, $hisiaddr );
if ( send( SOCKET, $MESG, 0, $hispaddr ) ) {
print "reboot of phone ", "$phone_ip", " was successful", "\n";
}
else { print "reboot of phone ", "$phone_ip", " failed", "\n"; }
}
exit;
this is my code so far:
class Driver
{
static void Main(string[] args)
{
if (!String.IsNullOrEmpty(args[0]))
{
var phone_ip = args[0];
SipMessage newMsg = new SipMessage(phone_ip);
IPAddress addr = IPAddress.Parse(phone_ip);
IPEndPoint end_point = new IPEndPoint(addr, 5060);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
byte[] send_buffer = Encoding.ASCII.GetBytes(newMsg.ToString());
Console.WriteLine("sending message: " + newMsg.ToString());
socket.SendTo(send_buffer, end_point);
Console.WriteLine("Sent message to " + phone_ip);
}
else Console.WriteLine("Message did not send");
}
}
class SipMessage
{
private string _to, _from, _call_id, _msg;
private DateTime _time;
public SipMessage(string p_ip = "")
{
_to = p_ip;
_from = "<sip:test>";
_time = DateTime.Now;
_call_id = _time.ToString() + "msgto" + _to;
_msg = String.Format("NOTIFY sip:" + _to + ":5060 SIP/2.0" +
"\nVia: SIP/2.0/UDP " + _to +
"\nFrom: {0};tag=1530231855-106746376154 " +
"\nTo: <sip:{1}:5060> " +
"\nEvent: check-sync " +
"\nDate: {2} " +
"\nCall-ID: {3} " +
"\nCSeq: 1 NOTIFY " +
"\nContact: {0} " +
"\nContent-Length: 0 ", _from, _to, _time, _call_id);
}
public override string ToString()
{
return _msg;
}
}
}
i have run the code and tested on a phone but it won't kick start the event. Am I on the right track? Am i missing something?
As an alternative you could use my C# sipsorcery nuget package.
using System;
using System.Net;
using System.Threading;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using SIPSorcery.Sys.Net;
namespace SipSendNotify
{
class Program
{
private const int _defaultSIPUdpPort = SIPConstants.DEFAULT_SIP_PORT; // The default UDP SIP port.
private static SIPTransport _sipTransport;
static void Main(string[] args)
{
try
{
// Configure the SIP transport layer.
_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
// Use default options to set up a SIP channel.
var localIP = LocalIPConfig.GetDefaultIPv4Address(); // Set this manually if needed.
int port = FreePort.FindNextAvailableUDPPort(_defaultSIPUdpPort);
var sipChannel = new SIPUDPChannel(new IPEndPoint(localIP, port));
_sipTransport.AddSIPChannel(sipChannel);
SIPCallDescriptor callDescriptor = new SIPCallDescriptor("test", null, "sip:500#67.222.131.147", "sip:you#somewhere.com", null, null, null, null, SIPCallDirection.Out, null, null, null);
SIPNonInviteClientUserAgent notifyUac = new SIPNonInviteClientUserAgent(_sipTransport, null, callDescriptor, null, null, (monitorEvent) => { Console.WriteLine("Debug: " + monitorEvent.Message); });
notifyUac.ResponseReceived += (resp) => { Console.WriteLine(resp.ToString()); };
notifyUac.SendRequest(SIPMethodsEnum.NOTIFY);
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne();
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp);
}
finally
{
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
}
In querying "YAS_YLD_SPREAD" for multiple securities, I am trying to assign a different override value for the "YAS_BOND_PX" override of each (as per Excel snapshot)
However, I am doing something wrong in assigning the overrides, as the output does not return a single "YAS_YLD_SPREAD" for each security (it also spuriously returns a "YAS_YLD_SPREAD 1") and the values returned are not the 100.21, 645.06 values I expect/need
Grateful for your help,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArrayList = System.Collections.ArrayList;
using Event = Bloomberglp.Blpapi.Event;
using Element = Bloomberglp.Blpapi.Element;
using Message = Bloomberglp.Blpapi.Message;
using Name = Bloomberglp.Blpapi.Name;
using Request = Bloomberglp.Blpapi.Request;
using Service = Bloomberglp.Blpapi.Service;
using Session = Bloomberglp.Blpapi.Session;
using SessionOptions = Bloomberglp.Blpapi.SessionOptions;
using InvalidRequestException =
Bloomberglp.Blpapi.InvalidRequestException;
using Subscription = Bloomberglp.Blpapi.Subscription;
namespace COATI
{
public class BloombergFetch
{
public string[] IsinArray;
private const String APIREFDATA_SVC = "//blp/refdata";
private static readonly Name SECURITY_DATA =
Name.GetName("securityData");
private static readonly Name SECURITY = Name.GetName("security");
private static readonly Name FIELD_DATA = Name.GetName("fieldData");
private static readonly Name RESPONSE_ERROR =
Name.GetName("responseError");
private static readonly Name SECURITY_ERROR =
Name.GetName("securityError");
private static readonly Name FIELD_EXCEPTIONS =
Name.GetName("fieldExceptions");
private static readonly Name FIELD_ID = Name.GetName("fieldId");
private static readonly Name ERROR_INFO = Name.GetName("errorInfo");
private static readonly Name CATEGORY = Name.GetName("category");
private static readonly Name MESSAGE = Name.GetName("message");
private ArrayList d_securities = new ArrayList();
private ArrayList d_fields = new ArrayList();
private ArrayList d_overrides = new ArrayList();
private ArrayList d_overridevalues = new ArrayList();
static void Main()
{
BloombergFetch example = new BloombergFetch();
example.run();
System.Console.WriteLine("Press ENTER to quit");
System.Console.Read();
}
public void run()
{
string serverHost = "localhost";
int serverPort = 8194;
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.ServerHost = serverHost;
sessionOptions.ServerPort = serverPort;
System.Console.WriteLine("Connecting to " + serverHost + ":" +
serverPort);
Session session = new Session(sessionOptions);
bool sessionStarted = session.Start();
if (!sessionStarted)
{
System.Console.Error.WriteLine("Failed to start session.");
return;
}
d_securities.Add("XS0975256685 Corp");
d_securities.Add("XS1207058733 Corp");
d_fields.Add("YAS_YLD_SPREAD");
d_fields.Add("YAS_YLD_SPREAD");
d_overrides.Add("YAS_BOND_PX"); d_overridevalues.Add(116);
d_overrides.Add("YAS_BOND_PX"); d_overridevalues.Add(88);
try
{
sendRefDataRequest(session);
}
catch (InvalidRequestException e)
{
System.Console.WriteLine(e.ToString());
}
// wait for events from session.
eventLoop(session);
session.Stop();
*/
}
private void sendRefDataRequest(Session session)
{
if (!session.OpenService(APIREFDATA_SVC))
{
System.Console.Error.WriteLine("Failed to open service: " +
APIREFDATA_SVC);
return;
}
Service refDataService = session.GetService(APIREFDATA_SVC);
Request request = refDataService.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement("securities");
Element overrides = request.GetElement("overrides");
for (int i = 0; i < d_securities.Count; ++i)
{
securities.AppendValue((string)d_securities[i]);
}
Element fields = request.GetElement("fields");
for (int i = 0; i < d_fields.Count; ++i)
{
fields.AppendValue((string)d_fields[i]);
}
for (int i = 0; i < d_overrides.Count; ++i)
{
Element bboverride = overrides.AppendElement();
bboverride.SetElement("fieldId",d_overrides[i].ToString());
//bboverride.SetElement("fieldId", "YAS_BOND_PX");
bboverride.SetElement("value", Convert.ToBoolean(d_overridevalues[i]));
//bboverride.SetElement("value", 100);
}
System.Console.WriteLine("Sending Request: " + request);
session.SendRequest(request, null);
}
private void eventLoop(Session session)
{
bool done = false;
while (!done)
{
Event eventObj = session.NextEvent();
if (eventObj.Type == Event.EventType.PARTIAL_RESPONSE)
{
System.Console.WriteLine("Processing Partial Response");
processResponseEvent(eventObj);
}
else if (eventObj.Type == Event.EventType.RESPONSE)
{
System.Console.WriteLine("Processing Response");
processResponseEvent(eventObj);
done = true;
}
else
{
foreach (Message msg in eventObj.GetMessages())
{
System.Console.WriteLine(msg.AsElement);
if (eventObj.Type == Event.EventType.SESSION_STATUS)
{
if (msg.MessageType.Equals("SessionTerminated"))
{
done = true;
}
}
}
}
}
}
private void processResponseEvent(Event eventObj)
{
foreach (Message msg in eventObj.GetMessages())
{
if (msg.HasElement(RESPONSE_ERROR))
{
System.Console.WriteLine("REQUEST FAILED: " +
msg.GetElement(RESPONSE_ERROR));
continue;
}
Element securities = msg.GetElement(SECURITY_DATA);
int numSecurities = securities.NumValues;
System.Console.WriteLine("Processing " + numSecurities + " securities:");
for (int i = 0; i < numSecurities; ++i)
{
Element security = securities.GetValueAsElement(i);
string ticker = security.GetElementAsString(SECURITY);
System.Console.WriteLine("\nTicker: " + ticker);
if (security.HasElement("securityError"))
{
System.Console.WriteLine("\tSECURITY FAILED: " +
security.GetElement(SECURITY_ERROR));
continue;
}
Element fields = security.GetElement(FIELD_DATA);
if (fields.NumElements > 0)
{
System.Console.WriteLine("FIELD\t\tVALUE");
System.Console.WriteLine("-----\t\t-----");
int numElements = fields.NumElements;
for (int j = 0; j < numElements; ++j)
{
Element field = fields.GetElement(j);
System.Console.WriteLine(field.Name + "\t\t" +
field.GetValueAsString());
}
}
else System.Console.WriteLine("No fields");
}
}
}
}
}
I haven't read your code in detail but one obvious issue is that if you want to use a different overriden value for the two securities, you need to submit two separate requests.
If you submit one request for XS0975256685 only with the YAS_BOND_PX override set to 116, you should get the desired result (I got 101.8739 a minute ago which matches Excel's result at the same moment).
Also note that the returned value does change with the market so you may get different values at each run: refresh your Excel spreadsheet at the same time if you want to verify that the data match.