How to establish web socket on server side for chat implementation? - websocket

If i don't have server details then who will establish or install the web socket connection? Can admin (who handle our host) establish connection and provide me the URL of websocket to use in android or angular code?
Is this necessary to write code in php?
I expect server admin install and configure web socket and provide to use in chat module.

Web admin(Ops) can help create the domain name but you have to write serverside code to handle websocket connection. You can use any programming language that supports websocket. for example,
nodejs - https://github.com/websockets/ws
java - https://docs.oracle.com/javaee/7/api/javax/websocket/package-summary.html
With java websocket you simply can define ServerEndpoint and deploy the war(web archive) to any host or cloud provider(Amazon cloud, google cloud etc),
#ServerEndpoint("/chat/{clientId}")
public class MyWebsocketServer {
#OnMessage
public String handleMessage(#PathParam("clientId") String clientId,
String message,
Session session) {
System.out.println("chat message: " + clientId + "/" +message);
return "hi how are you doing?";
}
}
Now, with javascript as a client your code to establish WebSocket connection would be:
var clientId = Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
var webSocket = new WebSocket("ws://localhost:8080/my-app/chat/" + clientId);
localhost means I'm running both Server and Client in same host, in your case serving host might be www.mike-simons.com/chat while client running on phone
Example: https://github.com/duwamish-os/chat-server_websocket-java

Related

How to create multiple XMPP clients in nodejs using websockets

I have an electron app that creates a websocket connection to a node js server. It sends a JSON request to that server telling it to create a xmpp client.
let message = {
action: "setupXmpp",
data: {
username,
password,
},
};
socket.send(JSON.stringify(message));
Within that server I have a switch that reads the message action and creates the xmpp client. The code in xmppActions is standard boilerplate taken from xmpp's repo
const xmppActions = require("./Webapp/xmppActions");
case "setupXmpp":
console.log(`Received setupXmpp request`);
var { username, password } = message.data;
const xmpp = xmppActions.setUpXMPPconn(username, password);
xmpp.on("online", async (address) => {
console.log("▶", "online as", address.toString());
ws.send("Register xmpp Success!");
});
break;
Everything works fine I can create an xmpp client and send messages, all good.
My issue is when i have two clients open and they both register (with different username and password ) whoever is the last request always overrides the previous register. I've done a wireshark trace and the two websocket connections are created as I would expect but when it comes to sending messages they both use the most recent register. I assume it's because the XMPP client is a constant and whoever is last it uses those for all future requests.
How do I make it so that each websocket connection gets its own XMPP client almost like a request scoped client specific for each websocket.
I had a constant outside the websocket connection, changed it to have a var inside so each connection had it own client.

Connect Laravel echo from Angular project

I have a Laravel-echo-server with Redis running on my local.
I created a test API endpoint, that emits broadcastable event.
on http://localhost:8000/api/web-socket-test I see the response in echo server CLI.
I set-up laravel-echo auth key and I can get the stat info from server API
http://localhost:6001/apps/APP_ID/status?auth_key=b73a61d0.
The problem is with connecting to echo-server from Angular via ws: protocol.
My connection code is
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
export class MyComponent implements OnInit, OnDestroy {
myWebSocket: WebSocketSubject<any> = webSocket('ws://127.0.0.1:6001');
ngOnInit() {
this.myWebSocket.subscribe(
msg => console.log('message received: ' + msg),
err => console.log(err),
() => console.log('complete')
);
}
And finally I've got an error: WebSocket connection to 'ws://127.0.0.1:6001/' failed: Connection closed before receiving a handshake response.
How can I establish ws connection?
I believe you want to try connecting using the socket.io client libraries instead of using rxjs raw websockets.
Although it's not immediately clear from the laravel echo server docs, the project title states it's a 'Socket.io server for Laravel Echo'. So I'm assuming you should use the socket.io client libraries for connections.

HttpRequestException - A connection with the server could not be established - UWP Web API

I have a uwp app which access web api link (which returns a json array) using HttpClient. It was working well with local host and remote host. But now when tries to access the webapi which is in remote host shows an exception "A connection with the server could not be established". User can able to browse that API through device where the app has been installed and can see the json files. But cant access the link within the app.
I have got same issue before in local host. And it is resolved by enabling local loopback for uwp
checknetisolation loopbackexempt -a -n=packagefamilyname
But how can I resolve it in remote host?
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://###/***/");//web api link is here
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response1 = await client.GetAsync("api/details");
response1.EnsureSuccessStatusCode(); // Throw if not a success code.
}

How to connect to django channel socket?

I followed the tutorial on the official site of the django channels. Everything is fine. But now, how do I connect to the ongoing socket and push message to the group in the server side (i.e. via django) ?
In the tutorial, following line of code in the js opens up a WebSocket connection simply by calling the WebSocket constructor:
var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/');
And I want to connect to the same socket in the server side. I tried this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('ws://127.0.0.1/ws/chat/2', 6379))
but I get error saying
socket.gaierror: [Errno -2] Name or service not known
I am a complete beginner in socket programming, and apologize if there is anything minor that I may have skipped.

gsoap Server does not accept Client request

I have created a web service in gsoap, but server does not accept requests. There is no error, but i dont understand why it does not accept requests from client. I am pasting my client and server code here.
Clientcode
EnrollmentServiceSOAPProxy proxy;
_ns1__performRequest *req = new _ns1__performRequest();
_ns1__performRequestResponse *res = new _ns1__performRequestResponse();
if(proxy.performRequest(req, res) == SOAP_OK)
print "OK" // pseudo code for print.
else
print "Not Ok"
Server Code:
int __ns1__performRequest(soap *, _ns1__performRequest *ns1__performRequest, _ns1__performRequestResponse *ns1__performRequestResponse)
{
ns1__performRequestResponse->jobID = "1011";
return SOAP_OK;
}
The server is listening on localhost. but the request does not reach the server.
This is the WSDL file:https://www.dropbox.com/s/n2sdv51qmttp7vb/EnrollmentService.wsdl
I debugged the code, but it did not help me.
It happend with me before. In service definition i used different port, while the server was listening to different port. This seems your problem too.
The service endpoint may not be set to your server, but to whatever the WSDL defines as the server address. You should use EnrollmentServiceSOAPProxy proxy("URL"); with the URL that is your server's endpoint address (http://hostaddr or http://localhost:8000 when you run your server local on port 8000).

Resources