Android Client not able to connect to server in libgdx game - android

I need to connect to a server I've set up on my Mac, but the Android socket always fails to connect. If I run the libgdx game on my Mac and use "localhost" as the desired server to connect to, it works fine. I've included the relevant permissions in my Manifest file. I'm using the public ip address I found by just doing a google search for my ip. I've made sure the ports are consistent as well.
public class ClientServer implements AsyncTask<String> {
private int port;
private String serverAddress;
private DataOutputStream outStream;
//private DataInputStream inStream;
private MandelSample ms;
public ClientServer (String serverAddress, int port, MandelSample ms) {
this.serverAddress = serverAddress;
this.port = port;
this.ms = ms;
}
public String fetchData (MandelSample ms) {
SocketHints hints = new SocketHints();
Socket clientSocket = Gdx.net.newClientSocket(Protocol.TCP, serverAddress, port, hints);
outStream = new DataOutputStream(clientSocket.getOutputStream());
String messageIN="Default Message";
try {
outStream.write("This message is from Android".getBytes());
messageIN = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
} catch (IOException e) {
Gdx.app.log("ClientServer", "An error occured", e);
}
return messageIN;
}
#Override
public String call() throws Exception {
String s = fetchData(ms);
return s;
}
}
My logcat:
com.badlogic.gdx.utils.GdxRuntimeException: Error making a socket connection to 146.7.4.78:8080
02-24 09:51:59.872 16349-26646/com.mygdx.game W/System.err: at com.badlogic.gdx.net.NetJavaSocketImpl.<init>(NetJavaSocketImpl.java:51)
02-24 09:51:59.872 16349-26646/com.mygdx.game W/System.err: at com.badlogic.gdx.backends.android.AndroidNet.newClientSocket(AndroidNet.java:70)
02-24 09:51:59.872 16349-26646/com.mygdx.game W/System.err: at com.mygdx.game.ClientServer$override.fetchData(ClientServer.java:35)
02-24 09:51:59.872 16349-26646/com.mygdx.game W/System.err: at com.mygdx.game.ClientServer$override.access$dispatch(ClientServer.java)
02-24 09:51:59.873 16349-26646/com.mygdx.game W/System.err: at com.mygdx.game.ClientServer.fetchData(ClientServer.java:0)

Related

How to use the ip and port returned from a STUN server

hope your having a nice day . im building a Video Call application using XMPP and Jingle and direct ByteStream from phone to phone . in order to do so i noticed i need a stun server to get public ip and port of android devices and send them to the other party , im getting the public ip like this
InetAddress address = Inet4Address.getByName("stun.l.google.com");
MessageHeader sendMH = new
MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
ChangeRequest changeRequest = new ChangeRequest();
sendMH.addMessageAttribute(changeRequest);
byte[] data = sendMH.getBytes();
DatagramSocket s = new DatagramSocket(null);
localPort = s.getLocalPort();
s.setReuseAddress(true);
// s.bind(address);
DatagramPacket p = new DatagramPacket(data,
data.length,address,19302);
s.send(p);
DatagramPacket rp;
rp = new DatagramPacket(new byte[32], 32);
s.receive(rp);
MessageHeader receiveMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingResponse);
// System.out.println(receiveMH.getTransactionID().toString() + "Size:"
// + receiveMH.getTransactionID().length);
receiveMH.parseAttributes(rp.getData());
MappedAddress ma = (MappedAddress) receiveMH
.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
ip = ma.getAddress().toString();
port = ma.getPort();
Log.i("XMPP-Stabler",ma.getAddress().toString()+" "+ma.getPort());
s.close();
}catch (Exception e){
e.printStackTrace();
}
then i send the result to the other party and open up a SocketServer on this client using given port , but still i can not connect to this ServerSocket over internet , or probably i am doing some thing wrong ? can you please help me how should i use STUN or TURN results ? thanks
and here is my connecting side of Jingle just in case
otherTransport = (JingleS5BTransport)
jingle.getContents().get(0).getTransport();
ArrayList<JingleContent> contents = new ArrayList<>();
contents.add(content);
session = (JingleS5BTransportSession) JingleS5BTransportManager.getInstanceFor(connection).transportSession(new JingleSession(connection.getUser(),responderFullId,role,sessionId,contents) {
#Override
public XMPPConnection getConnection() {
return connection;
}
#Override
public void onTransportMethodFailed(String namespace) {
Log.i("XMPP-Stabler","transport method failed "+namespace);
}
});
session.setTheirProposal(otherTransport);
session.initiateOutgoingSession(new JingleTransportInitiationCallback() {
#Override
public void onSessionInitiated(BytestreamSession bytestreamSession) {
Log.i("XMPP-Stabler","ON SESSION INITIATED 2!");
Socks5BytestreamSession session = (Socks5BytestreamSession) bytestreamSession;
}
#Override
public void onException(Exception e) {
e.printStackTrace();
}
});

java.net.SocketException in Android AsyncTask

I am now working on creating simple
image server in Android.
This is the server class...
new Thread(new Runnable()
{
public void run()
{
try
{
ServerSocket serverSocket = new ServerSocket(8080);
while(true)
{
Socket client = serverSocket.accept();
SimpleImageSender sender
= new SimpleImageSender(client);
sender.execute();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
and this is the AsyncTask.
public class SimpleImageSender extends HttpGetForMapTileHandler<Void,Void,Void>
{
protected Socket client;
public SimpleImageSender(Socket socket)
{
super();
this.client = socket;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
URL url = new URL("http://www.imageFromWeb.png");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setRequestMethod("GET");
httpCon.connect();
if(httpCon.getResponseCode() == 200)
{
DataOutputStream out = new DataOutputStream(this.client.getOutputStream());
byte response[] = new byte[BUFFER_SIZE];
int index = httpCon.getInputStream().read(response,0,BUFFER_SIZE);
while(index != -1)
{
out.write(response,0,index);//***
index = httpCon.getInputStream().read(response,0,BUFFER_SIZE);
}
out.flush();
}
else
{
Log.d("AAA","No png");
}
}
catch(Exception e)
{
e.printStackTrace();
cancel(true);
}
return null;
}
}
When I tested this code in Android 6.0(Nexus 5), Java.net.SocketException
occers when the line //*** called more than twice.
This is the call stack I got.
09-06 18:03:42.763 20730-22167/com.example.SimpleImageSenderServer
W/System.err: java.net.SocketException: sendto failed: ECONNRESET
(Connection reset by peer)
09-06 18:03:42.763 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at
libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:542)
09-06 18:03:42.763 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at libcore.io.IoBridge.sendto(IoBridge.java:511)
09-06 18:03:42.764 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at
java.net.PlainSocketImpl.write(PlainSocketImpl.java:500)
09-06 18:03:42.764 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at java.net.PlainSocketImpl.-
wrap1(PlainSocketImpl.java)
09-06 18:03:42.764 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at
java.net.PlainSocketImpl$PlainSocketOutputStream.
write(PlainSocketImpl.java:266)
09-06 18:03:42.764 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at
java.io.DataOutputStream.write(DataOutputStream.java:98)
09-06 18:03:42.765 20730-22167/com.example.SimpleImageSenderServer
W/System.err: at
com.example.SimpleImageSenderServer.
SimpleImageSender.doInBackground(SimpleImageSender.java:xx)
I also want to imform that this error did not happen when I tested in
Android 4.4.2, 5.0 devices.
Virtual devices (Android 7.0).
I checked the java.net.SocketException issues through
the Internet but I could not figure it out
what was the cause.
Any advice will be very helpful.
Thank you
You can never to thread operations on the main thread. It has to be done async.
So you have two options. Either disable strictmode:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Or use an asynctask for the connection too
int index = httpCon.getInputStream().read(response,0,BUFFER_SIZE);
while(index != -1)
{
out.write(response,0,index);//***
index = httpCon.getInputStream().read(response,0,BUFFER_SIZE);
}
This is garbage, or at least poorly written and poorly named. read() returns a count, not an index. Try this:
int count;
while((count = httpCon.getInputStream().read(response)) > 0)
{
out.write(response,0,count);
}
// The following are completey missing from your code
out.close();
httpCon.getInputStream().close();
If you still get connection resets it is probably because the peer has closed the connection.

Bluetooth Code to send string In Android

I have got list of paired devices of Bluetooth.Now i want to send text to that particular paired device.I have done code for that.
Below is the code:
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
But i'm getting these Error:
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
04-05 10:53:41.356 5580-5580/? W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:900)
04-05 10:53:41.356 5580-5580/? W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:912)
04-05 10:53:41.356 5580-5580/? W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:531)
So, please help me how to solve this error.
What kind of device are you trying to connect to?
-> Based on discussion: If trying to connect to another phone running Android there must be application which is accepting the connection. Working example is available from Google: BluetoothChat
You can try speeding up the connection process:
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
Or you can try using different UUID (are there more supported)?
System.out.println(uuids);
Or you can try using insecure connection:
device.createInsecureRfcommSocketToServiceRecord(...)
BTW: Your code for reading data from inpust stream won't work very well. Take a look at example from Google Chat Application: BluetoothChatService

Android client to java server

I want to create an application on android that checks if user is in the server database. At this moment, i just try to make connection work.
This is my client code :
public class Client {
public void testConnexion() {
new LoadTesting().execute();
}
class LoadTesting extends AsyncTask<String, String, String> {
private final String HOST_ADDRESS = "23.248.21.91";
private final Integer HOST_PORT = 2009;
#Override
protected String doInBackground(String... params) {
Socket socket;
try {
Log.d("CASERVER", "Connexion...");
InetAddress srvAddress = InetAddress.getByName(HOST_ADDRESS);
socket = new Socket(srvAddress, HOST_PORT);
Log.d("CASERVER", "Connexion successful !");
// DO SOMETHING
socket.close();
} catch (IOException e) {
e.printStackTrace();
Log.w("CASERVER", e.getMessage(), e);
}
return null;
}
}
}
And the server part
public class Server {
public static final int HOST_PORT = 2009;
public static void main(String[] args) {
ServerSocket serverSocket;
Socket socketDuServeur;
try {
serverSocket = new ServerSocket(HOST_PORT);
socketDuServeur = serverSocket.accept();
// DO SOMETHING
serverSocket.close();
socketDuServeur.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have add those permission
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
My server is on my macbook connected to my wifi.
I've got two Eclipse Window : one for android and one for the server.
The test :
1 Launch the server, the server is waiting for connection
2 Launch the application on the mobile device and try to connect the server
I expect the result :
Connexion...
Connexion successful ! (Or an error)
I've got the following Log result instead :
Connexion...
No error, no successful. Just nothing...
When i shut down manually the server (with another client on laptop) i've got EHOSTUNREACH error (device can't found the server)
Can you help me ?

Broadcasting with WiFi Direct in android

I am beginner in android programming. Am trying to broadcast messages on WiFiDirect using the following code:
public class FileTransferService extends IntentService {
public static final String host= "255.255.255.255";
InetAddress broadcastAddress = InetAddress.getByName(host);// Exception: Unknown host exception
int port = 8888;
protected void onHandleIntent(Intent intent) {
Log.d(WiFiDirectActivity.TAG,"m in 1");
Context context = getApplicationContext();
DatagramSocket socket;
try {
socket = new DatagramSocket(port);
socket.setBroadcast(true);
socket.connect(broadcastAddress, port);
String message = "Hello";
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, broadcastAddress, port);
socket.send(packet); // <----- Causes a SocketException
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.getMessage(), e);
}
}
}
It shows me unknown host exception on getByName() method. Is there anyway to replace the method? Am I going on a right path? Do I need to add anything along with this to send messages.
Thanks in advance
Try calling public UnknownHostException (String detailMessage) to get the detailed exception message.
Another way to call getByName() can be get from here
Below link has a step by step illustration of setting up a Wi-Fi Direct broadcaster
Connecting with Wi-Fi Direct

Categories

Resources