What I am trying to do is start a local server on my Android Device and from a Chromecast connect to the Android Server so that I can send image data from the android to a Chromecast.
What I've done so far is set up a ServerSocket on the Android that is binded to the 127.0.0.1 and then send the localhost information (port number) in a message to the chromecast which tells it the serversocket is ready to accept connections and instructs the Chromecast to connect to the server. But I have no idea how I should be connecting to it. I've tried using WebSockets to connect to the ServerSocket but I'm getting
WebSocket connection to 'ws://localhost:9147/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I've changed the port number, tried both "ws" and "wss" and I've tried searching for the answer but everything I've come across has been "how to connect android to a server" or "how to connect an Android server to an Android client" so I appologize if this is a repost.
What I was planning on doing is using Base64 image encoding to send a String with the image data to the chromecast and then set the image src to that. I obviously not want to do this using Cast.CastAPI.sendMessage().
To be clear, I am looking for a way to connect to an Android server using JavaScript.
The Android code runs fine, the Chromecast gets the message but when it tries to connect it fails.
Android Code:
Runnable bitmapSender = new Runnable() {
private ServerSocket serverSocket;
public static final int SERVERPORT = 9147;
#Override
public void run() {
Socket socket = null;
try {
Log.d(TAG, "Socket binding attempt");
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SERVERPORT));
String message = createJsonMessage(MessageType.socket, "wss://localhost:"+ SERVERPORT);
sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
Log.d(TAG, "Socket thread");
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
BitmapExecutorService.execute(commThread);
}catch(IOException e){
e.printStackTrace();
}
}
}
};
Javascript:
function connectToSocket(source){
//Connect to socket
window.socket = new WebSocket(source);
socket.onopen = function() {
socket.send('Hello Android');
};
window.socket.onmessage = function(event) {
console.log('Received a message from the server!', data);
var jsonObj = JSON.parse(event.data)
if(jsonObj.type == "image"){
console.log('Image sent :)');
var source = 'data:image/png;base64,'.concat(jsonObj.data)
displayEncodedImage(source);
}
};
Thanks
edit: Update
I was trying to connect through localhost. This didn't work like I thought it would. I still haven't got the image sending working but I now have the handshake. What I needed to do was send the IP Address of the phone. I did so by adding the ACCESS_WIFI_STATE permission to the manifest and obtaining the IP Address with the following code:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Related
I´m trying to implement a websocket in my spring boot application, but I´m unable to create a connection.
I used this video and its corresponding git-repo to create the following config for the server and the javascript code for the client.
Server
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gameplay");
registry.addEndpoint("/gameplay").withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
Client
const url = 'http://localhost:8080';
let stompClient;
let paymentId;
function connectToSocket() {
console.log("Trying to open connection to /gameplay");
let socket = new SockJS("/gameplay");
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log("connected to the frame: " + frame);
stompClient.subscribe("/topic/game-progress", function (response) {
console.log("data");
let data = JSON.parse(response.body);
console.log(data);
})
})
}
The server-console doesn´t have any entries, so I guess there is something wrong with the javascript part. In the browser-console it says:
Trying to open connection to /gameplay
Opening Web Socket...
GET http://localhost:8080/gameplay/info?t=1620312392571 404
Whoops! Lost connection to http://localhost:8080/gameplay
I tried...
using different URLs to establish the connection
http://localhost:8080/gameplay
http://localhost:8080/app/gameplay
/gameplay
/app/gameplay
Using the URLs from the first bullet point to establish a connection using Chrome´s advanced REST client. I got the message "Unknown error occured"
Adding .setAllowedOrigins("*") to my stompEndpointRegistry like suggested here
Does anyone know...
Where the last part of the request (/info?t=1620312392571 )comes from and could it be causing the malfunction?
If I need to write "http:localhost.8080" before the socket URL? Some people do that, others don´t.
How I can get this working?
In others questions the root of the problem had something to do with the dependencies. I included all the dependencies that fixed the problem for other users so I. don´t think the dependencies are the problem. However, here is a link to my pom.xml.
I´m thankful for all kind of help.
I was also facing same issue. Update client code as
let socket = new SockJS("/app/gameplay");
Don't modify below server code
registry.addEndpoint("/gameplay").withSockJS();
I'm trying to connect java Server and Javascript client with socket.io. When i see the debugger at browser, it looks like the data is being received, but i'm getting this error: "Reason: CORS header 'Access-Control-Allow-Origin' missing" and i am not being able to print data at client-side.
import...
public class MeuServerSocket {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public MeuServerSocket(int port) {
// starts server and waits for a connection
try {
while(true){
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
saida.flush();
// send available data from server to client
saida.writeObject("Texto enviado 123...");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
boolean fim = false;
while (!line.equals("Over") && !fim)
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
fim = true;
System.out.println(i.toString());
}
}
System.out.println("Closing connection");
// close connection
socket.close();
saida.close();
in.close();
}
} catch (IOException i) {
System.out.println(i);
}catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String[] args) {
MeuServerSocket server = new MeuServerSocket(5000);
}
}
var socket = io('http://localhost:5000');
socket.on('connect', function () {
socket.send('hi \nOver');
socket.on('get', function (msg) {
// my msg
console.log('msg: '+msg)
})
socket.on('disconnect',()=>{
console.log('disconnected')
})
})
When i look at Firefox network, i see that the data was sent inside one of the packages...
https://imgur.com/vDAS00B
The biggest issue I'm seeing here is a misunderstanding of socket.io. Socket.io for javascript is not compatible with the Socket library in java. The naming conventions can be confusing for sure.
socket.io is a library that is related to web sockets (ws://). It implements all the basic websocket features plus some bonuses.
What you have for your java code is a TCP socket server. While websockets and socket.io are built on TCP socket, you can not connect a socket.io client to a "naked" socket server.
SOLUTION:
If your javascript is running from nodejs, you can use their net library found here. If you are running javascript from a webbrowser, than you are limited to websockets, which means you're going to change your java code to a websocket server. You can find a library for that somewhere online.
TLDR: Use ws://... instead of http://....
Details:
https is used for HTTP protocol. In such case it is correct that browser first asks your server if CORS is allowed. You have not enabled CORS. That's why it is normal that browser refuses to send CORS request.
But you say you want to use Web Sockets. Then you should use ws://, not http://. For Web Sockets there is no CORS policy and browser will send your request without CORS restrictions.
I had been wrote a simple javax websocket app. I'm trying to send data from #OnOpen method via session to client like this
#OnOpen
public void onOpen(Session session) throws IOException {
session.getBasicRemote().sendText("Client connected");
}
then I'm trying to recieve it, but got undefined on client
ws.onopen = function(event) {
document.getElementById('messages').innerHTML = event.message;
};
or
ws.onopen = function(event) {
document.getElementById('messages').innerHTML = event.data;
};
Could we get it?!
add: also a same thing with #OnError
Based on the JSR 356, if you read the OnOpen part, there are parameters like session, configs and path params but there is nothing you get for a message from the client. So maybe you can use path params to get the data?
Hi I'm trying to upload image via the Java script port. Logging seems to work and it seems the server is not receiving the "file" object. Here is my code (note this works via simulator):
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picture = (String) evt.getSource();
if (picture != null) {
String url = "...";
MultipartRequest request = new MultipartRequest();
request.setUrl(url);
try {
request.addData("file", picture, "image/png");
request.setFilename("file", "myPicture.png");
request.setPost(true);
request.addArgument("submit", "yes");
NetworkManager.getInstance().addToQueueAndWait(request);
Log.p("initVars(..) MultipartRequest error code: "
+ request.getResponseCode(), Log.DEBUG);
String data = new String(request.getResponseData());
Log.p(data, Log.DEBUG);
} catch (IOException err) {
err.printStackTrace();
}
}
}
}, Display.GALLERY_IMAGE);
If the JavaScript deployed on the same server as the upload destination?
Assuming you are in the same server try using the build hint: javascript.inject_proxy=false. This will disable the proxy servlet and create direct communication to the JavaScript port.
If you are not in the same server make sure you are using the WAR distribution with the proxy servlet within so it can redirect your upload.
I'm using MVC 4. I have a js code that needs to communicate with the server with the help of Websockets. I'm using Fleck at the server. I'm creating the socket server in Application_Start event. But when I try the connection from browser console, I get errors like Connection refused.
Here is my global.asax code.
protected void Application_Start()
{
IPAddress ip = null;
if (GetResolvedConnecionIPAddress(out ip)) // Get host ip
{
string Domain = "wss" + System.Uri.SchemeDelimiter + ip + ":" + "8092";
FleckLog.Level = Fleck.LogLevel.Debug;
try
{
if (GetResolvedConnecionIPAddress(out ip))
{
var server = new WebSocketServer(Domain);
server.Start(socket =>
{
LogWriter.Logger.Info("WS: Inside socket server");
socket.OnOpen = () =>
{
LogWriter.Logger.Info("WS: OnOpen socket");
};
socket.OnClose = () =>
{
LogWriter.Logger.Info("WS: OnClose socket");
};
socket.OnMessage = message =>
{
LogWriter.Logger.Info("WS: OnMsg socket");
};
});
}
}
catch (Exception e)
{
throw;
}
}
}
It looks like as soon as the Application_Start method ends, that WebSocketServer is going to get out of scope and eventually garbage collected.
You could, set that object as member in the Global class, and dispose it on the Application_End event for example.
UPDATE:
You are also using the wss schema but not providing any certificate configuration. Please note that IIS and Fleck are two different things, that runs in different ports, and not because you create Fleck into the ASP.NET app means that Fleck is going to infer the SSL/TLS configuration or any configuration at all. Try to set the schema to ws instead and open the page without HTTPS and see if it works.