I'm creating a simple chat program that connects two android devices and they can send simple message
I run the server with Socket on a port (1234 for example)
The problem is from the client i do not know the server IP Address. (and i dont want to enter it manually)
is there a way to find a server that is running on a specific port?or can i run the server on some specific static IP that i can give it to clients?
if not is there another way to communicate with android devices that works on Android 2.2+(don't want to use wifi direct) ?
Thanks in Advance
You can broadcast a udp message from the server specifying your ip in the message. Let the client receive the broadcast and use that msg as the ip address to connect to the socket. (PS : The broadcast receiver must b allowed to receive broadcasts). And you are done!
Assign one SERVER predominantly for getting details such as IP ADDRESS, PORT number,etc.. from all the clients.
Each client when activated will contact the SERVER to register itself first and will get the details(IP ADDRESS,etc) of other device to communicate.
Now they can start waiting for specific device.
On 4.1 you can use Mutlicast DNS for service discovery via the NsdManager (if you are on the same network). If you need this to work over the Internet/3G there is really no good way to do it. You could use Google Cloud Messaging (GCM) to notify clients about the server address, but in any case you will need one 'real' server on a stable address that all participants can reach.
http://developer.android.com/reference/android/net/nsd/NsdManager.html
InetAddress.getLocalHost(); doesnot work for me but ya below code work for me
DhcpInfo dhcp = mWifiManager.getDhcpInfo();
int dhc = dhcp.serverAddress;
String dhcS = ( dhc & 0xFF)+ "."+((dhc >> 8 ) & 0xFF)+"."+((dhc >> 16 ) & 0xFF)+"."+((dhc >> 24 ) & 0xFF);
dhcS contains IP address of server,I used for Wireless connection between multiple devices.
You can use this code
connectionSocket.getRemoteSocketAddress();
No the port can never be fixed with a IP. It is always provided by the user. To know the IP address of the server automatically, you can run this program associated with the chat program.
public class Net {
public Net() throws UnknownHostException {
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia);
ia = InetAddress.getByName("local host");
System.out.println(ia);
}
public static void main(String args[]) throws UnknownHostException {
Net a = new Net();
}
}
You run can this program by the help of a button which is associated with your chat program.
Related
Was following this link to connect devices using Wifi direct to send message between two devices (device A with android 4.3 and Device B 7). When I try to connect client (device A) to server (device B) to transfer data using
socket.connect(new InetAddress(host, port)), 500);
It always gives UnknownHostException.
P.S - Device B is groupOwner. (checked using ConnectionInfo). IP address of groupOwner is always 192.168.49.1.
Any help will be appreciated.
You must make sure a Wi-Fi Direct connection is established, then the GO automatically runs the DHCP to assign IP addresses to itself (192.168. 49.1/24)
I need to implement the communication among all the devices connected to same WiFi AP. I am using the Google Nearby Connections APIs. I am able to connect to multiple device and communicate. But due to some problem connection getting lost. I have checked the Google documentation, It suggest that "When a device is connected to the host, it may send messages to other client devices."
https://developers.google.com/nearby/connections/android/manage-connections
My doubt is what it mean "it may send messages to other client devices".
If multiple client devices are connected to a Host device, then how a client device can send a message to other client devices?
I never tried this, but it seems you can get the clients endpointId with Nearby.Connections.getLocalEndpointId() on the client devices. Not sure how this helps sending messages to other clients, because the host knows the Client-EndpointIds anyway...
However, as a proof of concept you could do something like this:
In the Host:
String payload = client2EndpointId;
Nearby.Connections.sendReliableMessage(mGoogleApiClient, client1EndpointId, payload);
In the Client1:
#Override
public void onMessageReceived(String endpointId, byte[] payload, boolean isReliable) {
String client2EndpointId = (String) payload;
Nearby.Connections.sendReliableMessage(mGoogleApiClient, client2EndpointId, messageFromClient1ToClient2);
}
And in Client2:
#Override
public void onMessageReceived(String endpointId, byte[] payload, boolean isReliable) {
String messageFromClient1 = (String) payload;
}
The Host sends client2's EndpointId as a message to client1. Client1 then uses this endpointId to send a message to client2.
Connections when using Nearby Connections API are lost when
you or other device gets disconnected to wifi
you and other device are connected to different wifi network (remember you are Nearby Connection which works on local network, if you want to send message via different network use Nearby Message API)
connection is lost even if the application in one of the device is minimised, closed(destroyed) etc
so I think you should log some of these cases.
"it may send messages to other client devices"
developer page mean that a connection status (Accepted, Rejected etc) can be send when the host responds to the connection request.
If multiple client devices are connected to a Host device, then how a
client device can send a message to other client devices?
And, if multiple devices are connected you can send your message (or I should rather say Data) to the host which will send the same data to all the clients connected to it (That's how most of the Host-Client system works).
I hope it helped
i have recently implement wifi direct into my project,my aim is pass string value between two wifidirect connected devices when some of my app condition satisfies.right now i have listed all peers and also made connection between the selected peer.now i need to pass String values to the connected devices..how can i pass string between two connected device. i have checked the [Wifi Direct chat][1]
[1]: https://github.com/life0fun/wifi-direct-chat project but it is very complicated.so any one suggest me any idea how can i pass the String values between two connected wifi device.(If code is needed i will post the code here)
you can use socket to connect between two peers in the same network.
for instance create a server socket on one of the peers on any port and then from the client side connect to that port on the other user . then you can use this socket connection to send strings, file whatever you want.
for starters i would recommend you employ the server socket on the group owner so it will be easier on your client side to get the ip of the peer(i.e group owner) using the groupOwnerAddress field provided by the api
refer to this -> http://www.oracle.com/technetwork/java/socket-140484.html
You can get text chat code from your installed SDK sample just goto
\sdk\samples\android-22\legacy\WiFiDirectServiceDiscovery
import that code into your eclipse, this is great sample in this text chating has been done nicely and code is too easy to understand.
I hope it will help you.
I use this code
luugiathuy.com/2011/02/android-java-bluetooth/
The server side is the PC
the client is the device, with the app based on bluetooth chat example
The device (galaxy tab 7.0) can establish connection with the PC.
However the PC server (written in java and bluecove) did nothing, as nothing is connected.
The loop for trying to find connected device is
while(true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
Output on PC:
uuid: 0000110100001000800000805f9b34fb
waiting for connection...
EDIT: source downloadhttps://github.com/luugiathuy/Remote-Bluetooth-Android
Same issue I got when I was trying in linux. But the reason (still not sure) when you run the bluetooth android application without turning on the Java server using bluecove, It will try to connect with the already installed bluetooth software. You may see the bluetooth icon asking for granting access to the mobile device.
To solve this, I just changed the uuid in the server and application (say from 1103 to 1101 and vice versa) and then started the server first and then the android application. Java server part started listening.
The reason I think may be the uuid when it did not found the bluecove stack service server, it got connected to the device server listening on same uuid. So after changing the uuid and making sure that the server is running before launching the android application should solve the issue.
If you are getting connected to the bluetooth system application and not to the Java bluecove server,
1) First change the uuid both server and android application.
2) Second make sure your server is running and listening on same uuid.
3) Launch the android application which try to communicate on same rfcomm connection uuid.
Server part code I took from : http://www.jsr82.com/jsr-82-sample-spp-server-and-client/
Library : http://code.google.com/p/bluecove/downloads/list
Yes, it happens with me too, I suggest you to fire following commend on shell, when it shows waiting for connection.
hcitool cc 58:C3:8B:D7:FA:F4
here 58:C3:8B:D7:FA:F4 is my device's bluetooth address, which should be replaced by your device's bluetooth address.
To get your device's bluetooth address, just start bluetooth in your device with discoverable mode and execute hcitool scan command, it will display all the active device with their name and bluetooth address.
Well you may run the above hcitool cc 58:C3:8B:D7:FA:F4 command via Java code as follows,
try
{
Process p=Runtime.getRuntime().exec("hcitool cc 58:C3:8B:D7:FA:F4");
}
catch ( Exception e )
{
}
The output from your program says it listens on UUID 0x1101. Is that true? The sample you reference shows it listening on a different UUID. Its Service Class Id is 0x04c6093b and is set as follows:
34 UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
35 String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
36 notifier = (StreamConnectionNotifier)Connector.open(url);
The two need to match on client and server.
I'm trying to listen on a port using ServerSocket on an Android device. I want to be able to connect to this port over WiFi using a computer on the same network.
I get no exception when binding it to a port, however when I check netstat it says:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 (null):4040 (null):* LISTEN
I've tried countless ways of binding it to localhost, 0.0.0.0, the WiFi LAN IP address of the device with SocketInetAddress and InetAddress.getByName. Nothing seems to work.
When I try to connect to the port from a computer in the same WiFi (I've tried both netcat and Java's Socket.connect()), all I can see in Wireshark is an ARP request:
Who has [phone's LAN address]? Tell [computer LAN address].
This request repeat itself until timed out.
I've tried the reverse way, by setting the ServerSocket on the computer and connecting to that port from the phone, that works very well.
My testing phone is an Samsung Spica i5700 with a custom ROM.
Any ideas?
Edit:
The code is simple as this:
ServerSocket server = new ServerSocket();
server.setReuseAddr(true);
server.setTimeout(0);
server.bind(new InetSocketAddress(4040));
Socket client = null;
while((client = server.accept()) == null);
// Connected
enter code here
enter code here
Instead of using server.bind, try initializing the server socket like this:
server = new ServerSocket(4040);
Also, server.accept() will actually block until a connection is made, so you don't need that while loop (see: http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#accept() )
I struggled with this too and was only able to connect to my Android server by using:
ServerSocket myServerSocket = new ServerSocket();
String hostname = getLocalIpAddress();
myServerSocket.bind(new InetSocketAddress(hostname, myPort));
Where hostname was the local IP, which I got using the getLocalIpAddress() function from this page:
https://github.com/Teaonly/android-eye/blob/master/src/teaonly/droideye/MainActivity.java
I was able to get this working by using
ServerSocket server = new ServerSocket( myTcpPort, 0, addr );
where addr = InetAddress of your phone. Otherwise, it only seems to bind to localhost (127.0.0.1). Also, I'm using port 8080.