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.
Related
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.
In chrome extension, I use native messaging to call the local application. But I found an issue that everytime I reload the extension, it seems like a new process is created for the application. By the documentation, the app will be ended if the port is disconnected or the page is closed. Does that mean reload extension won't close the background page? How can I solve this problem? Also, I cannot find my local application process in the chrome task manager.
// background.js
var port = null;
connectToNativeHost();
// Receive message from other js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("background recieved message from " + sender.url + JSON.stringify(request));
parseMessage(request);
}
);
//onNativeDisconnect
function onDisconnected()
{
console.log(chrome.runtime.lastError);
console.log('disconnected from native app.');
port = null;
}
// Receive message from native app
function onNativeMessage(message)
{
console.log('recieved message from native app: ' + JSON.stringify(message));
}
//connect to native host and get the communicatetion port
function connectToNativeHost()
{
var nativeHostName = 'com.group_project.time_tracker';
port = chrome.runtime.connectNative(nativeHostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
console.log("connected");
}
// Send message to native app
function sendMessage(message)
{
port.postMessage(message);
console.log('send messsage to native app: ' + JSON.stringify(message));
}
so i switched to HTTPS, everything worked nicely exept the sockets.
If I try to visit website with the HTTP, the sockets connect, but if I try to connect with HTTPS I get:
The Error on Console:
Failed to load resource: net::ERR_CONNECTION_CLOSED
Failed to load resource: net::ERR_CONNECTION_CLOSED
Failed to load resource: net::ERR_CONNECTION_CLOSED
Failed to load resource: net::ERR_CONNECTION_CLOSED
Frontend:
function connect()
{
if (!SOCKET)
{
var hash = getCookie('hash');
if (hash == "") {
//$.notify('You must login!', 'success');
}
if (hash != "") {
$.notify('Connecting...', 'success');
}
SOCKET = io(':3001');
SOCKET.on('connect', function(msg) {
if (hash != "") {
//$.notify('Connected!', 'success');
}
SOCKET.emit('hash', {
hash: hash
});
$('#games tr').remove();
});
SOCKET.on('connect_error', function(msg) {
$.notify('Connection lost!', 'success');
});
SOCKET.on('message', function(msg) {
onMessage(msg);
});
SOCKET.on('disconnect', function(m) {
SOCKET.emit('disconnect', {
uhash: hash
});
});
}
else
{
console.log("Error: connection already exists.");
}
}
Node.js/Backend
var httpsOptions = {
cert: fs.readFileSync("/path/to/cert/cert.pem"),
ca: fs.readFileSync("/path/to/cert/chain.pem"),
key: fs.readFileSync("/path/to/cert/privkey.pem"),
}
var server = require('https').createServer(httpsOptions);
var io = require('socket.io').listen(server);
server.listen(3001);
Your Node application should only accept HTTP connections. Your Apache server should be responsible for the HTTPS. This simplifies your app, and allows Apache to load balance for you if you ever decide to do so.
So between your app and Apache should be HTTP, and then HTTPS between Apache and the client. There are many guides on how to do this, I suggest reading the official documentation
If you decide to go against this, and implement SSL at the web app level (not recommended), then we'll need more information.
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.
In the netframework v2, the socket use the Invoke (BeginRead) method to call a method (example ReceiveMsg) as below:
client = new TcpClient();
client.Connect(SERVERIP, PORTNO);
data = new byte[client.ReceiveBufferSize];
SendMessage("hello\n");
client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMsg, null);
Will this method ReceiveMsg of socket always be in "Auto Mode" such that it will standby to receive the message broadcast by SocketServer?
or It is using System.Threading.Thread.Sleep() to make ReceiveMsg method always active so that it will be in ready mode to respond to when SocketServer broadcast message?
How to do this in Netframework v4 or 4.5 socket for this ReceiveMsg method as BeginRead() is no longer required.
Thanks.
Below is the code for socket in netframework v4 :http://msdn.microsoft.com/en-us/library/hh202858(v=vs.92).aspx (for WP mango/ Wp8)
Client.Connect();
Client.Send();
Client.Receive();
public string Receive()
{
//-- receive the reply from server
string response = "Receiving Operation Timeout";
// We are receiving over an established socket connection
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
// Setup the buffer to receive the data
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
// Inline event handler for the Completed event.
// Note: This even handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Receive request over the socket
_socket.ReceiveAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS seconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}