Reputation: 194
I am trying to connect my swift app to my web socket backend. On my backend I am using node, express and socket.io. My server is running correctly and I am able to connect to it and use the web sockets from my react web app. I am struggling to achieve the same result with swift. I am using socket.io-client-swift library to connect. My server is secure, I will used https://test.api.com
as my address for this.
My socket connection in my react app looks as follows:
const socket = io('https://test.api.com', {
secure: true,
forceNew: true,
reconnectionAttempts: 'Infinity',
timeout: 30000,
transports: ['websocket']
})
My swift connection code looks as follows:
class Socket: NSObject {
static let shared = Socket()
override init() {
super.init()
let manager = SocketManager(socketURL: URL(string: "https://test.api.com")!)
manager.setConfigs([.secure(true), .log(true)])
log.warning("Setting up socket connection")
let socket = manager.defaultSocket
socket.on(clientEvent: .connect) {data, ack in
log.warning("Socket connected")
}
log.warning("Connecting...")
socket.connect(timeoutAfter: 15) {
log.warning("Can't connect to socket server")
}
}
}
My error log looks like this:
LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
LOG SocketIOClient{/}: Joining namespace /
LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
LOG SocketManager: Adding engine
LOG SocketManager: Manager is being released
LOG SocketEngine: Starting engine. Server: https://test.api.com
LOG SocketIOClient{/}: Client is being released
LOG SocketEngine: Handshaking
LOG SocketEnginePolling: Doing polling GET https://test.api.com/socket.io/?transport=polling&b64=1
ERROR SocketEnginePolling: Error during long poll request
ERROR SocketEngine: Error
LOG SocketEngine: Engine is being released
My server initialisation for the socket looks as follows:
// Add websocket
var allowedOrigins = "http://localhost:*";
const socketConfig = {
origins: allowedOrigins,
pingTimeout: 60000
}
io = require('socket.io')(server, socketConfig);
Upvotes: 0
Views: 3721
Reputation: 194
I figured out the issue. On the server I was only allowing localhost in the socket config. This worked on the react app as it was running locally. When I removed the origins everything worked correctly. The socket server initialization looks as follws:
// Add websocket
var allowedOrigins = "http://localhost:*";
const socketConfig = {
// origins: allowedOrigins, -- Removed this line
pingTimeout: 60000
}
io = require('socket.io')(server, socketConfig);
Upvotes: 1