WebSockets in firefox - c#

For implementing my websocket server in C# I'm using Alchemy framework. I'm stuck with this issue. In the method OnReceive when I try to deserialize json object, I get a FormatException:
"Incorrect format of the input string." (maybe it's different in english, but I'm getting a localized exception message and that's my translation :P). What is odd about this is that when I print out the context.DataFrame I get: 111872281.1341000479.1335108793.1335108793.1335108793.1; __ad which is a substring of the cookies sent by the browser: __gutp=entrystamp%3D1288455757%7Csid%3D65a51a83cbf86945d0fd994e15eb94f9%7Cstamp%3D1288456520%7Contime%3D155; __utma=111872281.1341000479.1335108793.1335108793.1335108793.1; __adtaily_ui=cupIiq90q9.
JS code:
// I'm really not doing anything more than this
var ws = new WebSocket("ws://localhost:8080");
C# code:
static void Main(string[] args) {
int port = 8080;
WebSocketServer wsServer = new WebSocketServer(port, IPAddress.Any) {
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect,
OnConnected = OnConnected,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, 5, 0)
};
wsServer.Start();
Console.WriteLine("Server started listening on port: " + port + "...");
string command = string.Empty;
while (command != "exit") {
command = Console.ReadLine();
}
Console.WriteLine("Server stopped listening on port: " + port + "...");
wsServer.Stop();
Console.WriteLine("Server exits...");
}
public static void OnReceive(UserContext context) {
string json = "";
dynamic obj;
try {
json = context.DataFrame.ToString();
Console.WriteLine(json);
obj = JsonConvert.DeserializeObject(json);
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
}
On the C# side I'm using Newtonsoft.Json, though it's not a problem with this library...
EDIT:
One more thing - I browsed through the code in here: https://github.com/Olivine-Labs/Alchemy-Websockets-Example and found nothing - I mean, I'm doing everything the same way authors did in this tutorial...
EDIT:
I was testing the above code in Firefox v 17.0.1, and it didn't work, so I tested it under google chrome, and it works. So let me rephrase the question - what changes can be made in js, so that firefox would not send aforementioned string?

I ran into the same issue - simply replacing
var ws = new WebSocket("ws://localhost:8080");
with
var ws = new WebSocket("ws://127.0.0.1:8080");
fixed the issue for me.

In C# console app I connect the client to the server using :
var aClient = new WebSocketClient(#"ws://127.0.0.1:81/beef");
Your code above is connecting using
var ws = new WebSocket("ws://localhost:8080");
There could be one of two issues -
First is to see if WebSocketClient works instead.
To make sure your url is of the format ws://ur:port/context. This threw me off for a while.

Related

Xamarin.Forms gRPC Error starting gRPC call: unexpected end of stream on Connection

i programming an Application for my study.
I try to use gRPC in Xamarin.Forms.
The gRPC is in a seperate Libyry (.NET Standart 2.1).
If i use the code in WPF-Core Project every thing works fine.
But if I try to use the same in my Xamarin.Forms-Project the Connection don't work.
if I use the connectionString "http://my.server.com:5050" I get these Exception
Error starting gRPC call: unexpected end of stream on Connection{my.server.com:5050, proxy=DIRECT hostAddress=5.189.149.82 cipherSuite=none protocol=http/1.1} (recycle count=0)
if I the SSL Version"https://my.server.com:5050" I get these Exception
Error starting gRPC call: Connection closed by peer
Here is the Code of the gRPC-Libary
...
if (connectionString.Contains("http://"))
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
channel = GrpcChannel.ForAddress(connectionString);
client = new Haushaltsbuch.HaushaltsbuchClient(channel);
SuccsessReply reply = new SuccsessReply { Result = false };
try
{
reply = client.Login(new UserRequest
{
User = new GRPC_User
{
Username = username,
PassHash = passHash
}
});
}
catch (RpcException e) when (e.Status.Detail.Contains("The SSL connection could not be established"))
{
client = null;
throw new CommunicationException("Fehler mit SSL-Zertifikat des Servers", e);
}
catch (RpcException e)
{
client = null;
throw new CommunicationException("Server nicht erreichbar", e);
}
...
I am only a student and if I google, then it says that Xamarin Forms is supporting gRPC.
But why is it not working?
the .Android Project has the GRPC.Core package from NuGet istalled.
Solved it by Replacing
channel = GrpcChannel.ForAddress(connectionString);
with
if (connectionString.Contains("http://"))
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
string newConString = connectionString.Replace("http://", "");
return new Channel(newConString, ChannelCredentials.Insecure);
}
else
{
string newConString = connectionString.Replace("https://", "");
return new Channel(newConString, new SslCredentials());
}
It seems like the GrpcChannel Class isn't working on Andriod.
Update: May, 2021
Xamarin does not fully support gRPC, so be aware of this when developing your software on Xamarin.Forms.
Starting w/ gRPC version 2.34.X, gRPC has started partial support for Xamarin.Forms w/ Android and iOS devices.
Please see this for more information.

Task hang infinitely when calling .Wait() in kafka-net

I'm currently trying to post messages from a for-loop on a kafka server running on my local machine using the kafka-net library in c# (https://github.com/Jroland/kafka-net), following the example given on the linked repo, my code is the following.
string kafkaServer = "http://" + ip + ":" + port;
Uri uri = new Uri(kafkaServer);
var options = new KafkaOptions(uri);
var router = new BrokerRouter(options);
var client = new Producer(router);
...
foreach(string sumup in LS){
payloadJson["fullPathDataFolder"] = remoteFolder;
payloadJson["globalName"] = GloablName;
payloadJson["name"] = name;
payloadJson["text"] = sumUp + "\n";
payloadJson["type"] = type;
string payload = payloadJson.ToString();
KafkaNet.Protocol.Message msg = new KafkaNet.Protocol.Message(payload);
client.SendMessageAsync(topic, new List<KafkaNet.Protocol.Message> { msg }).Wait();
}
This code run through the first iteration and i'm able to retrieve the first string from a second machine linked to the same server with a consumer.
Then the code here above remain stuck at the intruction:
client.SendMessageAsync(topic, new List<KafkaNet.Protocol.Message> { msg }).Wait();
If now I remove the .Wait() this code run quite fast but it randomly ignore some of the string i send
What am I missing ?
P.S.
I'v tried also to use Confluent.kafka and i got similar problems
P.P.S.
It's important that this program run sequentially.

Connecting to IRC via a proxy (.NET)

I wish to hide my IP when connecting to IRC via my .NET app. I currently use the IrcDotNet library but it doesn't seems to support proxies.
I've not had much experience with sockets, so I think modifying IrcDotNet would be easier than making my own IRC library. I looked around for socket libraries that handle proxy connections that I could implement in IrcDotNet. I found one called ProxySocket but it only supports BeginConnect not the new ASyncConnect method that IrcDotNet uses.
To break it down, in order of preference, here's what I'm looking for;
An IRC library that supports connecting via a HTTP/SOCKS proxy
A socket library that supports connecting via a HTTP/SOCKS proxy via
ASyncConnect
Example code on how to extend the socket class to support connecting
via a HTTP/SOCKS proxy via ASyncConnect
The version of IrcDotNet I am using is 0.4.1 found at https://launchpad.net/ircdotnet.
Update 1: Still no luck i'm afraid. Fredrik92's answer, while helpful, is not applicable to the version of IrcDotNet I am using (see above).
The IRC.NET library uses the standard Socket class in the System.Net.Sockets namespace.
So you could just modify the IrcDotNet/IrcClient.cs file in the IRC.NET source code (# http://ircdotnet.codeplex.com/SourceControl/latest).
You should add a constructor for proxy enabled IRC clients and call the default constructor.
Then all you should need to do is to modify the Connect methods in the same file (almost at the bottom). Each time they call this.client.BeginConnect(..) you have to add code for connecting to the Proxy (instead of the remote host)
Now you only have to create a new Connect-callback method that sends a HTTP CONNECT request to the proxy. Read the response from the HTTP Proxy and then everything else should work.
In this case I would write the HTTP request as raw ASCII bytes to the Proxy (instead of using the HttpWebRequest class), so that you have full control over the network stream you get in return...
You should add sth. like this to the IrcClient class:
private bool useProxy = false;
private IWebProxy proxy;
private IEnumerable<Uri> proxyRemoteUris;
public IrcClient(IWebProxy proxy)
: this()
{
this.useProxy = true;
this.proxy = proxy;
}
private void ProxyPerformHttpConnect(Uri remoteIrcUri)
{
string httpConnectRequest = string.Format("CONNECT {0}:{1} HTTP/1.1\r\nHost: {2}\r\n\r\n",
remoteIrcUri.Host, remoteIrcUri.Port, this.proxy.GetProxy(remoteIrcUri));
byte[] httpConnectData = Encoding.ASCII.GetBytes(httpConnectRequest);
this.stream.Write(httpConnectData, 0, httpConnectData.Length);
bool responseReady = false;
string responseText = string.Empty;
// Byte-by-byte reading required, because StringReader will read more than just the HTTP response header
do
{
int readByte = this.stream.ReadByte();
if (readByte < 0)
throw new WebException(message: null, status: WebExceptionStatus.ConnectionClosed);
char readChar = (char)(readByte); // Only works because HTTP Headers are ASCII encoded.
responseText += readChar;
responseReady = responseText.EndsWith("\r\n\r\n");
} while (!responseReady);
int statusStart = responseText.IndexOf(' ') + 1;
int reasonStart = responseText.IndexOf(' ', statusStart) + 1;
int reasonEnd = responseText.IndexOfAny(new char[] { '\r', '\n'});
HttpStatusCode responseStatus = (HttpStatusCode)(int.Parse(responseText.Substring(responseText.IndexOf(' ') + 1, length: 3)));
if (responseStatus != HttpStatusCode.OK)
{
string reasonText = responseText.Substring(reasonStart, reasonEnd - reasonStart);
if (string.IsNullOrWhiteSpace(reasonText))
reasonText = null;
throw new WebException(reasonText, WebExceptionStatus.ConnectFailure);
}
// Finished Response Header read...
}
private void ProxyConnectCallback(IAsyncResult ar)
{
try
{
this.client.EndConnect(ar);
this.stream = this.client.GetStream();
bool proxyTunnelEstablished = false;
WebException lastWebException = null;
foreach (Uri remoteIrcUri in this.proxyRemoteUris)
{
if (this.client.Connected == false)
{
// Re-establish connection with proxy...
Uri proxyUri = this.proxy.GetProxy(remoteIrcUri);
this.client.Connect(proxyUri.Host, proxyUri.Port);
}
try
{
ProxyPerformHttpConnect(remoteIrcUri);
proxyTunnelEstablished = true;
break;
}
catch (WebException webExcept)
{
lastWebException = webExcept;
}
}
if (!proxyTunnelEstablished)
{
OnConnectFailed(new IrcErrorEventArgs(lastWebException));
return;
}
this.writer = new StreamWriter(this.stream, Encoding.Default);
this.reader = new StreamReader(this.stream, Encoding.Default);
HandleClientConnected((IrcRegistrationInfo)ar.AsyncState);
this.readThread.Start();
this.writeThread.Start();
OnConnected(new EventArgs());
}
catch (Exception ex)
{
OnConnectFailed(new IrcErrorEventArgs(ex));
}
}
The code for the proxy handling in all Connect methods of the IrcClient class would thus look sth. like this:
// Code snippet to insert before the call to this.client.BeginConnect(...)
if (this.useProxy)
{
// Assign host and port variables for EndPoint objects:
// var host = remoteEP.Address;
// var port = remoteEP.Port;
this.proxyRemoteUris = new Uri[] { new Uri(string.Format("irc://{0}:{1}/", host, port)) };
// Replace the line above with the following line in the method where an array of IP addresses is specified as a parameter
// this.proxyRemoteUris = from ip in addresses select new Uri(string.Format("irc://{0}:{1}/", ip, port));
Uri proxyUri = this.proxy.GetProxy(this.proxyRemoteUris.First());
string proxyHost = proxyUri.Host;
int proxyPort = proxyUri.Port;
this.client.BeginConnect(proxyHost, proxyPort, ProxyConnectCallback, registrationInfo);
}
else
// Original this.client.BeginConnect(...) call here...

Not able to connect to WCF-XMLRPC-Server using other client in a different language

I have created a sample xmlrpc C# server-client using Vaster Clemens tutorials
http://vasters.com/clemensv/PermaLink,guid,679ca50b-c907-4831-81c4-369ef7b85839.aspx
I am successfully able to connect to my C# server to the C# client, but whenever I try to connect to the C# server using my Java Client , I get only this error :
HTTP server returned unexpected status: Internal Server Error
Here is the C# server API exposed :
[ServiceContract]
public interface ITestAPI {
[OperationContract(Action = "test.returnSum")]
int returnSum(
int a,
int b);
This is the server part:
Uri baseAddress = new UriBuilder(Uri.UriSchemeHttp, Environment.MachineName, 8080, "/testDemo/").Uri;
ServiceHost serviceHost = new ServiceHost(typeof(TestAPI));
var epXmlRpc = serviceHost.AddServiceEndpoint(typeof(ITestAPI), new WebHttpBinding(WebHttpSecurityMode.None), new Uri(baseAddress, "./test"));
epXmlRpc.Behaviors.Add(new XmlRpcEndpointBehavior());
serviceHost.Open();
Console.ReadLine();
serviceHost.Close();
The C# client goes here :
Uri blogAddress = new UriBuilder(Uri.UriSchemeHttp, Environment.MachineName, PORT_NUMBER, pathValue).Uri;
ChannelFactory<ITestAPI> testAPIFactory = new ChannelFactory<ITestAPI>(new WebHttpBinding(WebHttpSecurityMode.None), new EndpointAddress(blogAddress));
testAPIFactory.Endpoint.Behaviors.Add(new XmlRpcEndpointBehavior());
testAPI = testAPIFactory.CreateChannel();
testAPI.returnSum(1,2);
After this I tried to implement a sample Java XML-RPC client given here and tried to connect it to the running C# server
http://www.tutorialspoint.com/xml-rpc/xml_rpc_examples.htm
public class JavaClient {
public static void main (String [] args) {
try {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:8080/testDemo/test"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
Vector params = new Vector();
params.addElement( new Integer(5) );
params.addElement( new Integer(5) );
Integer result = (Integer)client.execute( "returnSum", params );
if ( result != null )
System.out.println( "result" + result);
} catch (XmlRpcException exception) {
System.err.println("JavaClient: XML−RPC Fault #" +
Integer.toString(exception.code) + ": " +
exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: " + exception.toString());
}
}
}
And nothing works.
Any kind of help would be much appreciated.
I was able to solve this problem guys: the API is supposed to be called like this : client.execute( "test.returnSum", params ); from your client. i.e. the same string you mentioned in your operation contract.

How to Push data from C# to ZeroMQ and Pull from Node.JS or vice-versa?

Scenario:
I am trying to send a data (say String type) from C# сonsole application to Node.JS server through ZeroMQ.
Information:
Using clrzmq for c# and ZeroMQ libs for C# and Node.JS respectively
I am able to perform push-pull from Node.JS, also push - pull from C#.
So, one thing is confirmed that ZeroMQ - The Intelligent Transport Layer is installed on the machine (Windows 7 64-bit)
Issue:
I am not able to push data from C# Console app to Node.JS app (even tried vice-versa), both are on the same machine and on the same address i.e tcp://127.0.0.1:2222
Node.js code:
var zmq = require('zeromq.node');
var pull_socket = zmq.socket('pull');
pull_socket.connect('tcp://127.0.0.1:2222');
pull_socket.on('message', function (data) {
console.log('received data:\n');
console.log(data);
});
C# code:
namespace DataServiceEngine
{
class Program
{
static void Main(string[] args)
{
//clsApp App = new clsApp();
//App.appId = "001";
//App.name = "Back Office";
//Console.WriteLine("appId :" + App.appId + "\n");
//Console.WriteLine("name:" + App.name + "\n");
try
{
// ZMQ Context and client socket
using (var context = new Context(1))
{
using (Socket client = context.Socket(SocketType.PUSH))
{
client.Connect("tcp://127.0.0.1:2222");
string request = "Hello";
for (int requestNum = 0; requestNum < 10; requestNum++)
{
Console.WriteLine("Sending request {0}...", requestNum);
client.Send(request, Encoding.Unicode);
string reply = client.Recv(Encoding.Unicode);
Console.WriteLine("Received reply {0}: {1}", requestNum, reply);
}
}
}
}
catch (ZMQ.Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}
Question: Can anyone tell me what may be the reason or where am I doing wrong?
I had the same issue (but I issued a communication Node.JS -> Node.JS). To solve the problem I used to do sendersocket.connect("tcp://"+host+":"+port); at the sender and receiversocket.bindSync("tcp://*:"+port); at the receiver.
Hope this fix your problem.

Categories

Resources