I am trying to establish a socket connection between an Android and a UWP application over WiFiDirect. UWP application advertise itself enabling others to discover it. Android app search for available WiFiDirect device and connect with the UWP application.
I am successful in initialising and connecting over WiFiDirect between Android and UWP. But I am confused about creating Socket connection after WiFiDirect connection is made. More specifically I am hesitant on which side should i create ServerSocket and client-socket.
In Android side i have seen example of creating ServerSocket if the device is group-owner and vice-versa. But in UWP side I am not sure which one should i create.
Android side code to create socket:-
override fun onConnectionInfoAvailable(info: WifiP2pInfo?) {
if (info!!.groupFormed && info.isGroupOwner) {
// Creating ServerSocket
}
else if (info.groupFormed) {
// Creating Client Socket
}
}
On UWP side after connection request is received my sample code:-
private async void Listener_ConnectionRequestedAsync(
WiFiDirectConnectionListener sender,
WiFiDirectConnectionRequestedEventArgs args)
{
WiFiDirectConnectionRequest request = args.GetConnectionRequest();
WiFiDirectDevice _device = await WiFiDirectDevice.FromIdAsync(request.DeviceInformation.Id);
var endPoints = _device.GetConnectionEndpointPairs();
EndpointPair firstEndpoint = endPoints[0];
// Which socket connection should i create
// StreamSocket or StreamSocketListener
}
I have tried a hack in UWP which seems to work but I am not confident about it
if (firstEndpoint.LocalHostName.CanonicalName.EndsWith("1"))
{
// creating server socket
// StreamSocketListener and waiting for incoming connection
}
else
{
//Creating client socket
// StreamSocket and connecting with remote host
}
How should i decide create socket connection type in UWP side? Please provide the fundamental concept that i am missing here.
Related
I have created a new project using Android Studio with libgdx that tries to connect to a Node.js server that has a code like this:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var serv = server.listen(8080,function () {
var port = serv.address().port;
//a code I've found online to show on what adress im listening
//"Example app listening at http://192.168.178.15:8080"
require('dns').lookup(require('os').hostname(), function (err, add, fam) {
console.log('Example app listening at http://%s:%s', add, port);
})
});
io.on('connection', function(socket){
console.log("Connected!");
.
.
My app code
public void connectSocket(){
System.out.println("Connection to the socket has started");
try {
socket = IO.socket("http://192.168.178.15:8080");
socket.connect();
System.out.println("connected"); // says it's connected, but on app or emulator it's not
} catch(Exception e){
System.out.println(e);
System.out.println("not connected");
}
The problem
When i run my .jar or DesktopLauncher class everything works perfectly, I connect. The moment I use my phone or emulator i don't get an error, it tries to connect but nothing is logged about a connection. As if the app can't find a server.
what I've tried
I've tried all the things what i could find online:
android:usesCleartextTraffic="true"
turn off my firewall, allow node and all what is needed on there too
changing differend ip adresses where to connect on my app such as "localhost", public ip, all the IP adresses I've found on ipconfig and internet, "o.o.o.o" (all of them worked on my computer .jar, or application through android studio)
portfoward 8080 but not sure if i did it right
I am using a router if that gives any clues what goes wrong
I'm trying this for few days now and I'm out of things to try.
I've written a small file transfer program for android using standard Java sockets. The program works fine except for the following case:
I connect two android devices A and B over WiFi tethering connection. Device A is sharing the connection (enabled as wireless hotspot). When I run java server on A and client on B, the program works okay but when I run the server on device B, it can't accept any socket binding request from A. It doesn't throw any exception. Seems like the request is not reaching the server! However, both the devices are connected (ping test is okay in both directions). Can't I run socket server on a device connected as hotspot client? I thought once the networking is setup correctly, the application would work in any direction.
Also, Wireshark traces reveal nothing. What am I missing here? Please help! Here are my code snippets:
Server side (waiting for client connection):
while (true) {
try {
socket = serversocket.accept();
Runnable connectionHandler = new ConnectionHandler(
socket, fileArray, filepathNameArray,
SenderActivity.this, userID, handler);
new Thread(connectionHandler).start();
userID = userID + 1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I would appreciate any kind of help! Thanks in advance.
I am facing a tricky situation while working on a restricted network. Though I have my System Proxy Set to connect to my Web Server, Below are the two different behaviors observed from Web Browser and from Android Sockets .
1) With Proxy set, The Web Browser Request for the my server URL (host:port) goes well and I get 200 OK with valid Response Data from the Server.
2) With Android App, I do Host Reachability check before making my Connection Request. In Host reach-ability check , I create a java.net Socket and if it returns without any exception i consider my host as reachable. PSB for code snippet.
public static boolean isHostReachable(String hostname, int port) {
boolean isReachable = false;
Socket socket = null;
try {
socket = new Socket(hostname, port);
isReachable = true;
} catch (Exception e) {
.....
} finally {
....
}
return isReachable;
}
The whole logic of Host Reachability check works fine when in work from unrestricted network (lets say my home network).
The problem comes in the Host Reachability Socket Call , when I run my app from a restricted network (with Proxy Set to access my Server). Here my Socket Creation call does not return leading to host reach ability failure !!
There is a clear discrepancy between the browser and my app behavior in restricted network!!
My Question : While the Web Appllication works perfectly fine, What can be reason for the failure of above Socket Creation from Android leading to my Host Reachability failure in restricted network (with Proxy set in System Preference) and any suggestion for me to overcome this ?
I am trying to implement a simple Android application that sends and recieves packets to and from a plugin written for Openfire server. The plugin is meant to recieve packets from a client for further processing. So it is not a chat. The following code snippet shows my way of sending packets to the server:
ConnectionConfiguration configuration = new ConnectionConfiguration(
HOST, PORT);
Connection connection = new XMPPConnection(configuration);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
if (connection.isConnected()) {
Packet packet = new Message();
packet.setFrom("123456789#localhost");
packet.setTo("987654321#component.localhost");
connection.sendPacket(packet);
connection.disconnect();
}
HOST and PORT are predefined constants.
I tried to use code in if clause inside the plugin and it worked perfectlly - component recieves packets and works with them. However, in my Android application this code does not work - packets do not reach the component.
So, guys, if you have any suggestions I will be greatful for your help. Maybe I use wrong technique somewhere - I am new to XMPP and Openfire.
Update
There are all needed permissions in application's manifest. And HOST is equal to a static IP address of the PC running Openfire server.
private static final String HOST = "192.168.1.100";
private static final int PORT = 5222;
In order to send packets to a server you should login to it using login() or loginAnonymously() methods of org.jivesoftware.smack.Connection class.
Thanks mr. Flow for the hint.
Connect and Disconnect
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
Connection connection = new XMPPConnection(config);
// Connect to the server
connection.connect();
// Log into the server
connection.login("username", "password", "SomeResource");
....
// Disconnect from the server
connection.disconnect();
</code>
you should login first, here is the guide to manage connections http://www.igniterealtime.org/builds/smack/docs/latest/documentation/connections.html
I want to make connection to FMS (flash media server) in my android application.
Please suggest if there is any way to get connected to FMS via RTMP.
Have you had a look at the NetConnection class? It establishes an RTMP connection to a RTMP-capable server.
Establishing a connection is easy:
var nc:NetConnection = new NetConnection();
// Listen for the netstatus event
nc.addEventListener(NetStatusEvent.NET_STATUS, onStatus);
// Connect to your server
nc.connect("IP_GOES_HERE");
function onStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
// Connection has been established
}
}
Looks like you don't want to do it in Flash but in Java. There is one library I know off that implements RTMP on the client side which is Flazr.