I am trying to check the TCP connection to a localhost TCP server (ActiveMQ broker) using following code:
string host = "localhost";
int port = 61616;
using (TcpClient tcpClient = new TcpClient())
{
try
{
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
Console.WriteLine("Connected.");
TimeSpan ts = TimeSpan.FromMilliseconds(150);
if (!t.Wait(ts))
{
Console.WriteLine("The timeout interval elapsed.");
Console.WriteLine("Could not connect to: {0}", port);// ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString());
}
else
{
Console.WriteLine("Port {0} open.", port);
}
}
catch (UnauthorizedAccessException )
{
Console.WriteLine("Caught unauthorized access exception-await behavior");
}
catch (AggregateException )
{
Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
}
I stopped the localhost server (ActiveMQ broker), and tried to run the above code. It threw System.AggregateException. When I started the server and ran the code; it connects to the server.
According to the documentation of TcpClient.Connect it says it will throw one of the following:
ArgumentNullException
ArgumentOutOfRangeException
SocketException
ObjectDisposedException
SecurityException
NotSupportedException
Why will it throw System.AggregateException?
This
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
wraps your .Connect() call. And Task.Run() always throws AggregateException with the real exception inside it. In order to fix this either inspect the exception or even better use the asynchronous variant of .Connect():
Task t = tcpClient.ConnectAsync(host, port);
instead.
What i did finally is:
tcpClient.ReceiveTimeout = 5000;
tcpClient.SendTimeout = 5000;
tcpClient.Connect(host, port);
catch (SocketException) {
Console.WriteLine("Could not connect to: {0}", port);
Console.WriteLine("Socket exception. Check host address and port.");
}
It seems to be working.
Related
I'm trying to make my OpenShift Node.js app working, but the WS connection is not working. Client error is: connection refused.
Client side factory service:
var dataStream = $websocket(localStorageService.get('wsUrl'))
dataStream.onMessage(function(message) {
var call = JSON.parse(message.data)
if (fnMap[call.fn]) {
fnMap[call.fn](call.event, call.data)
}
})
dataStream.onError(function(err) {
console.log(err)
})
dataStream.onClose(function(event){
console.log('event: ' + JSON.stringify(event))
})
var fnMap = {
"broadcastResult": function(event, data) {
$rootScope.$broadcast(event, data)
}
}
var methods = {
callFn: function(paramJSON) {
dataStream.send(JSON.stringify(paramJSON));
}
}
return methods
I'm trying to connect on the following URL: ws://myapp-myname.rhcloud.com:8000
Could you please help?
Thank you in advance,
Csaba
First, you may want to make sure the websocket library, ws, is installed by declaring it in the dependencies section of your package.json and then doing another git push.
Otherwise, try the example provided in the openshift blog: https://blog.openshift.com/paas-websockets/
Specifically:
var websocket = new WebSocket("ws://myapp-myname.rhcloud.com:8000");
websocket.onopen = function(event) {
// The connection was opened
console.log(event)
};
websocket.onclose = function(event) {
// The connection was closed
console.log(event)
};
websocket.onmessage = function(event) {
// New message arrived
message = event.data
console.log(event)
};
websocket.onerror = function(event) {
// There was an error with your WebSocket
console.log(event)
};
The above at least might help point you toward a specific part of your code that's not working. Or, if the example isn't even working, it could be possibly something wrong with your cartridge, and you could try reaching out to RedHat's support.
i have simple web sockets html5 , when the server is up every thing is working fine
the problem is when i close the server ( for testing )
im getting :
WebSocket connection to 'ws://127.0.0.1:7777/api' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
which i unable to catch its never jumps to onerror or onclose in case of this error
init: function () {
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt) {
cc.log("Send Binary WS was opened.");
};
this.m_wsiSendBinary.onmessage = (function(evt) {
this.handleServerResponse(yStr);
this.m_wsiSendBinary.onerror = function(evt) {
};
this.m_wsiSendBinary.onclose = function(evt) {
cc.log("m_wsiSendBinary websocket instance closed.");
self.m_wsiSendBinary = null;
};
}).bind(this);
I do not have full answer, however I dealt with similar issue and have a partial and not so elegant solution (but may help someone). Unfortunately without the elimination of the error message.
Two business requirements:
BR1 - Handle state in initialization when the server is not available.
BR2 - Handle state when the server stops.
Solution for BR1
var global_connection_openned=null;//Here you have the result
init: function () {
global_connection_openned=false;
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt)
{
global_connection_openned=true;
};
Solution for BR2 (assumes the BR1)
//somewhere in your project called by setInterval(..) which will detect the connection is lost (and tries to reestablish/reopen the connetion.
{
if (this.m_wsiSendBinary==null || this.m_wsiSendBinary.readyState==3)
this.init();
if (!global_connection_openned)
this.m_wsiSendBinary=null;
}
Anyway, I would be really curious if there is solid and proper solution of this use case.
I'm trying to send an object type UserEntry to the client.
the route I used was: http://localhost:3027/api/userapi/getinfo?username=myUsername
What is the cause of this error or what is wrong with my code?
[HttpGet, Route("api/userapi/getinfo")]
public async Task<string> getUserInfo([FromUri]string username)
{
UserEntry u = await UserEntry.getUserInfo(username);
return new JavaScriptSerializer().Serialize(u);
}
Here is what inner exception shows:
InnerException: {
Message: "An error has occurred.",
ExceptionMessage: "Invalid operation. The connection is closed.",
ExceptionType: "System.InvalidOperationException",
StackTrace: " at System.Data.SqlClient.SqlConnection.GetOpenConnection() at System.Data.SqlClient.SqlConnection.get_ServerVersion()"
}
I checked and made sure that there was no error in connecting with the database, but it still shows error.
I temporarily solved it by making it synchronous
I solved it by making it synchronous
[HttpGet,Route("api/userapi/getinfo")]
public SimpleUser getUserInfo([FromUri]string username)
{
var ur = new UserRepository();
return ur.getUser(username).First();
}
public IEnumerable<SimpleUser> getUser(string username)
{
UserEntryDBContext context = new UserEntryDBContext();
UserEntry u = context.Users.Where( x => x.username == username).FirstOrDefault();
List<SimpleUser> s = new List<SimpleUser>();
s.Add(new SimpleUser(u));
return s;
}
but I still have no idea what causes the error nor how can I make it asynchronous.
When I try to send a message to another extension, occasionally I might have an invalid id (the extension may have been removed), but sendMessage does not ever notify me of this. As far as I can tell, it just prints to console.error:
This is miscellaneous_bindings Line 235 of Chrome's source code:
chromeHidden.Port.dispatchOnDisconnect = function( portId, errorMessage)
{
var port = ports[portId];
if (port) {
// Update the renderer's port bookkeeping, without notifying the browser.
CloseChannel(portId, false);
if (errorMessage) {
lastError.set(errorMessage, chrome);
//It prints: Port error: Could not establish connection. Receiving end does not exist.
console.error("Port error: " + errorMessage);
}
try {
port.onDisconnect.dispatch(port);
} finally {
port.destroy_();
lastError.clear(chrome);
}
}
};
As a result, my app is left trying over and over to send a message. The only hint I have is an empty response send back from sendResponse(), but any app can send an empty response object! How do I know it failed?
In the callback of sendResponse, look at the chrome.runtime.lastError property.
chrome.runtime.sendMessage("ID of extension", "message", function(response) {
var lastError = chrome.runtime.lastError;
if (lastError) {
console.log(lastError.message);
// 'Could not establish connection. Receiving end does not exist.'
return;
}
// Success, do something with response...
});
I try to use SecureSocket but SecureSocket.isSupported == false.
When I use simple Socket everything is ok.
Did anybody use SecureSocket?
here is my code:
Security.allowDomain('');
Security.allowInsecureDomain("");
Security.loadPolicyFile("xmlsocket://" + host + ':' + port + "/crossdomain.xml");
if(SecureSocket.isSupported)
{
c = new SecureSocket();
receiveBuffer = new ByteArray();
receiveBuffer.endian = Endian.LITTLE_ENDIAN;
c.addEventListener(Event.CLOSE, closeHandler);
c.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
c.addEventListener(Event.CONNECT, connectHandler);
}
else
{
try
{
c = new SecureSocket();
}
catch(e:Error)
{
trace(e.toString());
}
}
Later I have error:
[SWF] /assets/flash/ssl/Main.swf - 63,146 bytes after decompression
Error: Request for resource at tlssocket://game9.lgr.su:8081 by requestor from https://game9.lgr.su/assets/flash/ssl/Main.swf has failed because the server cannot be reached.
* Security Sandbox Violation *
Connection to game9.lgr.su:8081 halted - not permitted from https://game9.lgr.su/assets/flash/ssl/Main.swf
The problem was on server side. Our server side on Node JS was listening for NOT SECURE SOCKET but was getting SECURE connection. So when server responded with NOT encrypted content Socket on client side just closed.
So make better server.