Im working on a project that involves sending a string from an android phone to my laptop running a 32 bit windows VM (VMWare Fusion). After doing some searching on how to do such a thing, I get the client (phone) working, but for the server (laptop) end, it never seems to receive anything.
Im sharing bluetooth with the VM, & the device is paired to the host, yet when I send the data it connects to the host, but the VM running the "server" never seems to receive it.
I got the code for the receiver from here, but just for clarifying, heres the code im using for the receiver/server/VM:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
public class server {
// TODO: Update this to use the window, instead of the console
public void startServer() throws IOException {
// Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//UUID uuid = new UUID("00001101-0000-1000-8000-00805F9B34FB", false);
// Create the servicve url
String connectionString = "btspp://localhost:" + uuid + ";name=SpudSPPServer";
// open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
// Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect…");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
// read string from spp client
InputStream inStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String lineRead = bReader.readLine();
System.out.println(lineRead);
// send response to spp client
OutputStream outStream = connection.openOutputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
}
& in the main file:
public static void main(String args[]) throws IOException {
display d = new display();
server blueToothServer = new server();
d.makePanel();
if (selectFile.fileMissing()) {
d.feed.setText("File missing, creating new file");
selectFile.makeFile();
d.feed.setText("File created! Awaiting data...");
} else {
d.feed.setText("File found! Awaiting data...");
d.MACAddress.setText("MAC Address: " + LocalDevice.getLocalDevice().getBluetoothAddress().replace("-", ":").toUpperCase());
}
blueToothServer.startServer();
}
If you need the code for the client (phone), I can post that if asked
Figured it out, turns out it was on the VMs end, so I just installed windows normally as opposed to a VM, & that fixed it
Related
I am trying to send message from the android app to the python application in windows but it is not working.
Android app is working good but client created in windows using python is not starting it is showing error that:- Traceback (most recent call last):
File "client.py", line 14, in
s.connect((socket.gethostname(), 9876))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Here is my client.py file
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import socket
# In[2]:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9876))
# In[ ]:
while True:
msg = s.recv(1024)
print(msg.decode("utf-8"))
Here is my messageSender.java in android
package com.example.sockets;
import android.os.AsyncTask;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MessegeSender extends AsyncTask<String,Void,Void> {
Socket socket;
DataOutputStream dataOutputStream;
PrintWriter printWriter;
#Override
protected Void doInBackground(String... strings) {
String message=strings[0];
try {
socket = new Socket("192.168.1.6",9876);
printWriter= new PrintWriter(socket.getOutputStream());
printWriter.write(message);
printWriter.flush();
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Here is my Mainactivity.java file in android
package com.example.sockets;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.msgBox);
}
public void sendMsg(View view)
{
Toast.makeText(this, "Function is running", Toast.LENGTH_SHORT).show();
MessegeSender messegeSender =new MessegeSender();
messegeSender.execute(editText.getText().toString());
}
}
if you want to connect android app to python via sockets then do same as above in android but change the python file by -
#Imports Modules
import socket
import time
listensocket = socket.socket()
Port = 9876
maxConnections = 2
IP = socket.gethostname() #Gets Hostname Of Current Macheine
listensocket.bind(('',Port))
#Opens Server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))
#Accepts Incoming Connection
# (clientsocket, address) = listensocket.accept()
# print("New connection made!")
# running = True
#Main
while True:
(clientsocket, address) = listensocket.accept()
message = clientsocket.recv(1024).decode() #Receives Message
print(message) #Prints Message
# if not message == "":
# print(message) #Prints Message
#Closes Server If Message Is Nothing (Client Terminated)
# elif message =="":
# clientsocket.close()
# # running = False
I'm not sure of the exact situation, but if you are trying to connect over the internet you may want to look into this permission, or permissions like this one.
Android has a layer of security which does not allow connections unless the user using application grants the application permission. Look into the permissions for this. My answer may be just a starting point.
<uses-permission android:name="android.permission.INTERNET" />
Here are some resources:
How to add manifest permission to an application?
how to create Socket connection in Android?
I'm using OpenJDK 11 on Linux and I need to make sure all my web requests done with HttpURLConnection are properly closed and do not keep any file descriptors open.
Oracle's manual tells to use close on the InputStream and Android's manual tells to use disconnect on the HttpURLConnection object.
I also set Connection: close and http.keepAlive to false to avoid pooling of connections.
This seems to work with plain http requests but not encrypted https requests whose response is sent with non-chunked encoding. Only a GC seems to clean up the closed connections.
This example code:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class Test {
private static int printFds() throws IOException {
int cnt = 0;
try (Stream<Path> paths = Files.list(new File("/proc/self/fd").toPath())) {
for (Path path : (Iterable<Path>)paths::iterator) {
System.out.println(path);
++cnt;
}
}
System.out.println();
return cnt;
}
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("http.keepAlive", "false");
for (int i = 0; i < 10; i++) {
// Must be a https endpoint returning non-chunked response
HttpURLConnection conn = (HttpURLConnection) new URL("https://www.google.com/").openConnection();
conn.setRequestProperty("Connection", "close");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while (in.readLine() != null) {
}
in.close();
conn.disconnect();
conn = null;
in = null;
}
Thread.sleep(1000);
int numBeforeGc = printFds();
System.gc();
Thread.sleep(1000);
int numAfterGc = printFds();
System.out.println(numBeforeGc == numAfterGc ? "No socket leaks" : "Sockets were leaked");
}
}
prints this output:
/proc/self/fd/0
/proc/self/fd/1
/proc/self/fd/2
/proc/self/fd/3
/proc/self/fd/4
/proc/self/fd/5
/proc/self/fd/9
/proc/self/fd/6
/proc/self/fd/7
/proc/self/fd/8
/proc/self/fd/10
/proc/self/fd/11
/proc/self/fd/12
/proc/self/fd/13
/proc/self/fd/14
/proc/self/fd/15
/proc/self/fd/16
/proc/self/fd/17
/proc/self/fd/18
/proc/self/fd/19
/proc/self/fd/0
/proc/self/fd/1
/proc/self/fd/2
/proc/self/fd/3
/proc/self/fd/4
/proc/self/fd/5
/proc/self/fd/9
/proc/self/fd/6
/proc/self/fd/7
/proc/self/fd/8
Sockets were leaked
Changing to a http URL makes the sockets close correctly as expected without GC:
/proc/self/fd/0
/proc/self/fd/1
/proc/self/fd/2
/proc/self/fd/3
/proc/self/fd/4
/proc/self/fd/5
/proc/self/fd/6
/proc/self/fd/0
/proc/self/fd/1
/proc/self/fd/2
/proc/self/fd/3
/proc/self/fd/4
/proc/self/fd/5
/proc/self/fd/6
No socket leak
Tested with both OpenJDK 11 and 12. Did I miss something or is this a bug?
Turns out to be a bug after all: https://bugs.openjdk.java.net/browse/JDK-8216326
shutdownInput is now replaced by close in the latest builds of JDK 11 and 13 (but not 12).
I am trying to run a simple spp server with android and eclipse and it doesn't seem to be connecting is there competition for the UUID or? Also I am using the MAC address of my computer is that correct?
ConnectTest Code on android
Readout:
...In onCreate()...
...Bluetooth is enabled...
...In onStart()...
...In onResume...
...Attempting client connect...
...Sending Message to server...
Popup:
In onResume() and an exception occured during write: socket closed.
Eclipse sppserver code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
sampleSPPServer.startServer();
}
}
readout:
Address: A45E60EB3CE8
Name: DESKTOP-QD8I9B1
Server Started. Waiting for clients to connect...
I have a small program where a Server-Client program is getting connected on the same network, but the same program shows a connection time out error in the client program. I have connected the two systems using LAN cable.
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException ;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Since the code runs on the same computer, three possibilities come to my mind:
The problem can be either your firewall/access to port rights or having IP addresses as mentioned by other fellows.
You are setting the IP address of the server wrong.
The IP address of the server does not lie on the subnet mask of your network. If you have literaly connected the two computers with a cable (no routers in the middle) you probably haven't setup a DHCP, i.e., your ip addresses should be manually selected. If the ip is selected randomly, chances are your client computer can't find the server computer. try manually setting the ip addresses of both computers to an invalid address within the same subnet mask range and see if it works.
For example set the following addresses:
client IP: 192.168.1.10
subnetmask: 255.255.255.0
server IP: 192.168.1.11
subnetmask: 255.255.255.0
Connecting the two systems with a LAN cable is not sufficient. You have to ensure they have distinct IP addresses, are both in the same IP subnet, and/or have appropriate IP routing tables defined. More typically you would connect both via a router.
I have an InputStream from a Socket in Java.
The InputStream is a H.264 video live stream. I would like to send this Video InputStream to a red5 Media Server, so that other clients can watch it.
I found this example
package com.ryong21.example.publisher;import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.red5.server.messaging.IMessage;
import org.red5.server.stream.message.RTMPMessage;
import org.red5.server.stream.provider.FileProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher {
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher.class);
String publishName = "test";
String localFile = "2.mp3";
String host = "rtmpxn.91kge.com";
int port = 1935;
String app = "live";
IMessage msg = null;
int timestamp = 0;
int lastTS = 0;
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while(client.getState() != PublishClient.PUBLISHED){
Thread.sleep(500);
}
FileProvider fp = new FileProvider(new File(localFile));
Date begin = new Date();
log.debug(begin.toString());
while(true){
msg = fp.pullMessage(null);
if(msg == null){
log.debug("done!");
break;
}
timestamp = ((RTMPMessage)msg).getBody().getTimestamp();
Thread.sleep(timestamp - lastTS);
lastTS = timestamp;
client.pushMessage( msg);
}
Date end = new Date();
log.debug(end.toString());
client.stop();
}
}`
My problem is how to use this with a Sockets InputStream, instead of the File used in FileProvider. The InputStream is already in H.264 encoded.
Ok, after digging a little deeper into video streaming, i found out that i ll first have to convert the InputStream to a container format file. Possible container formats are .mp4 or .flv
Having created the container file, i can now publish it to the red5 media server.