WebSocket is closed before the connection is established [duplicate] - web-services

I'm using JavaScript and the Union platform How would I go about diagnosing this problem? Many thanks.

If you go to http://jsbin.com/ekusep/6/edit and view the JavaScript console you'll see the 'WebSocket is closed before the connection is established' logged. I've tested this in Chrome.
In this code what it means is that ws.close() was called (by user code) before the connection was even given a chance to be established.
So, the cause of this error is if code attempts to close the WebSocket connection before it's had a chance to actually connect.

In React you need to add this to your useEffect in return
useEffect(() => {
socket = new WebSocket(address);
return () => {
if (socket.readyState === 1) { // <-- This is important
socket.close();
}
};

For anybody else coming in to find an answer, apart from what #leggetter has mentioned above, in my case, it turned out that I was missing the port number while establishing a connection. I was using socket.io if that helps.
http://websocket.service:8000

Just open the port in server
ufw enable

Related

Multipeer Connectivity Not Connecting Programmatically

I am creating an iOS/macOS app that uses remote control functionality via the Multipeer Connectivity Framework. Since the device to be remotely monitored and controlled will run over an extended period of time, it's not viable to use the automatic view controller methods since the monitoring device may be locked or go to sleep and then disconnect the connection. So I'm using the programatic approach so that when the monitoring devices lose connection, they will automatically pair up when they are unlocked/woken up and the app is started again. My connection works fine using the ViewController method but not the programatic delegate approach. The advertising, browsing and inviting works fine, but when the invitation is accepted on the remote side I get several errors and then a failed connection. What's weird is that several of the errors are GCKSession errors.
So why is it trying to use the GameCenter framework? And why is it failing after accepting the invitation? Could it just be a bug in the Xcode 8 / Swift 3 /iOS 10 / macOS Sierra Beta SDKs?
[ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (2008493930)
[GCKSession] Wrong connection data. Participant ID from remote connection data = 6FBBAE66, local participant ID = 3A4C626C
[MCSession] GCKSessionEstablishConnection failed (FFFFFFFF801A0020)
Peer Changing
Failed
[GCKSession] Not in connected state, so giving up for participant [77B72F6A] on channel [0]
Here is the code from my connection class
func startAdvertisingWithoutUI () {
if advertiserService == nil {
advertiserService = MCNearbyServiceAdvertiser (peer: LMConnectivity.peerID, discoveryInfo: nil, serviceType: "mlm-timers")
advertiserService?.delegate = self
session.delegate = self
}
advertiserService?.startAdvertisingPeer()
}
func browserForNearbyDevices () {
if browserService == nil {
browserService = MCNearbyServiceBrowser (peer: LMConnectivity.peerID, serviceType: "mlm-timers")
browserService?.delegate = self
session.delegate = self
}
browserService?.startBrowsingForPeers()
}
func sendInvitation(to peer: MCPeerID) {
browserService?.invitePeer(peer, to: session, withContext: nil, timeout: 60)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: (Bool, MCSession?) -> Void) {
let trustedNames = GetPreferences.trustedRemoteDevices
for name in trustedNames {
if name == peerID.displayName {
invitationHandler(true,session)
return
}
}
invitationHandler (false, session)
}
None has worked for me.
I've resolved only disabling encryption...
let session = MCSession(peer:myPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.none)
When the peerID used to make the session and the peerID used to make the advertiser or browser do not match, I get this part of the error.
[GCKSession] Wrong connection data. Participant ID from remote connection data = 6FBBAE66, local participant ID = 3A4C626C
Once peerIDs match, that part of the error goes away.
There might still be some other connection problems though.
I found out what was wrong. The MCPeerID object that I was passing into the MCSession instances, I was vending it as a Computed Class Property instead of storing it as a Stored Property. So I changed it to a Stored Instance Property and everything started working! Thanks Tanya for pointing me in the direction of the MCPeerID object.
Old Code
// Class Properties
static var localPeer : MCPeerID { return MCPeerID(displayName: GetPreferences.deviceName!) }
New Code
// Instance Properties
let localPeer = MCPeerID (displayName: GetPreferences.deviceName!)
The problem for me was that I never set the delegate of MCSession. I got all the same error messages that the OP mentioned, which made me think the connection was broken, but really I just forgot to set the delegate. After setting the delegate, all the error messages still printed, but otherwise my delegate methods got called normally upon receiving a message!
I've inflicted this problem on myself twice. Hopefully this helps someone reading along!
I got to work with TViOS 10.0 beta with this ...
peerID = MCPeerID(displayName: UIDevice.current.name)
Although I am still seeing this error...
2016-09-08 10:13:43.016600 PeerCodeATV[208:51135] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (847172408)
2016-09-08 10:13:47.577645 PeerCodeATV[208:51155] [GCKSession] SSLHandshake returned with error [-9819].
Same problem for me with an app I've had on the itunes store for years.
The latest 10.1 beta update now seems to fix the bluetooth issue with my app without any change to my code.

Websocket broadcasting not working

I have an issue with my websocket.
I have recently switched my server from PHP to c++ side, and used the POCO library, i used exactly this script:
WebSocketServer.cpp
For the one client side in c++ i used a snipet i found here on stackoverflow:
WebSocketClient.cpp
I modified the client a bit, first it sends a default message as soon as i connect to the server.
I wrapped the whole thing with an Update function from my main app, that I am constantly able to recieve messages:
void CLeagueStats :: Update( ) {
if(m_Connected) {
string msg = Recv( );
if(msg != "") {
//handleIncomingMsg( msg );
}
} else if(GetTime() - LastReconnectTime > 90 || LastReconnectTime == 0) {
Connect( );
}
}
string CLeagueStats :: Recv( ) {
char receiveBuff[256];
int flags=0;
int rlen=m_psock->receiveFrame(receiveBuff,256,flags);
CONSOLE_Print("Recv: "+string(receiveBuff));
return string(receiveBuff);
}
I have now written a totally simple javascript client which is initalizing on page load:
<script type="text/javascript">
var ip_port = 'localhost:9980';
var ohc;
if (typeof (MozWebSocket) == 'function')
ohc = new MozWebSocket('ws://' + ip_port);
else
ohc = new WebSocket('ws://' + ip_port);
var self = this;
setTimeout(function() {
self.ohc.send("hey");
}, 500);
</script>
The server log includes both messages:
C++ App:
WebSocket connection established. Frame received (length=5, flags=0x81).
Javascript:
WebSocket connection established. Frame received (length=3, flags=0x81).
But the log from the C++ App does send the connection message and recieve it back, but i dont get the message from the js-client:
[Websocket] Connecting to websocket.
[Websocket] Send: hello
[Websocket] Recv: hello
Why this happen?
Isn't the snippet form the servercode directly sending the message back to all clients?
n = ws.receiveFrame(buffer, sizeof(buffer), flags);
app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", n,unsigned(flags)));
ws.sendFrame(buffer, n, flags);
Is there anything wrong with the code?
I am not a situation to reproduce the environment but I had a similar issue using Python and IOS web sockets. Every other technology we used was working in with Python Sockets flawlessly but IOS web socket had problem. After many days later we find out that IOS web socket does not send a communication ender (EOM) that Python can process. So the we had to handle different IOS sockets different.
I have checked WebSocket flags 81 so it is text and frame is finish. But I would suggest you to check from Developer Tools of browser to see what is recieved over the socket connection from Network Tab.
I may be problem of End of Message did not understood by javascript WebSocket. If you see the data hello on developer tools then it would be easy to handle with situation. However if you don't see any message coming then the problem is most probably from C++ code.
In attachment you can see how Chrome shows the socket data transactions. Keep in mind that clicking on the connection on the left list will update the transactions they are not live.
Hope this helps you.
If not go deeper using tcpdump or similar sowftware to be sure if they really sent and got by two sides.

c# app connectivity issue

I am new to C# and would be really grateful if someone could provide some insight on the following problem: I have written a c# app that gets the html content of a website, quite simply using a webclient. The problem is that if I run it for multiple websites I see that sometimes I get no results for some of them, like it was never connected to that website at that instance. I initially thought it was my internet connection but the same happened when I tried on a different wifi. It is worth mentioning that I have the same prob on another of my appcs when trying to connect to a webservice. My question is: does anybody know how can this be fixed? Does it have to do with the timeout time of something like that?
Thank you very much in advance
This is the code but it's not really an issue of coding:
var client = new WebClient();
try
{
var htmlcode = client.DownloadString(site);
int NumberOfTrues = Regex.Matches(htmlcode.ToLower(), key).Count;
}
catch (Exception)
{
messagebox.show("could not be loaded");
}
This was solved by defining the default proxy server in app config.

Replying to remote client via reply only?

According to the akka actor documentation one can reply using self.channel ! Message so the code will work locally. I would like to do the same with remote actors.
I have:
class ServerActor extends Actor {
def receive = {
case "Hello" =>
self.channel ! "World"
}
}
and
class ClientActor extends Actor {
val remote = ...
def receive = {
case "Start" =>
remote ! "Hello"
case "World" =>
println("World received")
}
}
This works in so far as the ServerActor receives the "Hello" and sends a "World" message to a ClientActor. Unfortunately, it seems that the ClientActor receiving the message is one that is created in the servers VM, not the one that actually sent it (in the client VM).
Is there a way to make this work?
PS: It works when I do a self reply "World" and remote ? "Hello", however, I would rather send a message than replying.
EDIT: Thanks to everyone. Starting remoting on both ends was the problem. Others finding this question beware:
When using letting clients receive their responses in a non-blocking manner (as in not using remote ? request), shutting them down immediately on receiving a shutdown message, will cause some strange behavior (mentioned in my comments below); possibly by design due (to akka's let-it-fail fault-tolerance?). As clients are not waiting for a response shutting them down immediately on receiving a shutdown message will result in the following (on akka-1.2): Since the "original clients" no longer exist (but the round-trip "is still in progress") they are restarted --- strangely --- both on the client and the server.
I think it is the same problem I had. You need to start up a server instance on the client aswell when you want receive messages from the server.
The exception is when you're explicitly are asking for a result with question-mark operator.

How to check if you have live internet connection programmatically using C++

How can I check if I have a internet connection or live internet connection using C++?
C++ has no builtin functions for this, you will need to resort to system APIs. An easiest and obvious way is to create a socket and try to connect it to some known IP or check if DNS is working.
Some useful links:
http://msdn.microsoft.com/en-us/library/ms740673(VS.85).aspx (Windows Sockets)
http://www.tenouk.com/cnlinuxsockettutorials.html (Linux/Unix sockets)
The easiest way is to try to connect to a known outside IP address. If it fails in Windows, the connect function will return SOCKET_ERROR, and WSAGetLastError will usually return WSAEHOSTUNREACH (meaning the packet couldn't be sent to the host). In Linux, you'll get back a -1, and errno will be ENETUNREACH.
For starters you can subscribe to the ISensIntf to check if you have a valid network connection. (Let me know if you need help in this. Its painful to register for the events etc.).
After that, you can use Api's like IsNetworkAlive, InternetGetConnectedStateEx or the InternetCheckConnection to check connectivity to the internet etc.
If your using C# or VB, then first Add a reference to
Microsoft.VisualBasic.Code.
Microsoft.VisualBasic.Devices.Network network = new Microsoft.VisualBasic.Devices.Network();
network.NetworkAvailabilityChanged += new Microsoft.VisualBasic.Devices.NetworkAvailableEventHandler(network_NetworkAvailabilityChanged);
...
private static void network_NetworkAvailabilityChanged(object sender, Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs e)
{
if (e.IsNetworkAvailable)
{
//network is connected.. do something..
}
else
{
//network isnt connected.. do something else.
}
Hope this helps