Usage of WiFi-Direct in Game Development (Android) - java

I am developing board game in android. I want to make this game playable on two separate devices, for that I need to use WiFi-Direct. I want to know is there any library available which will help me to
Find and connect with device
Send and receive board coordinates between two devices after touch-listener event
I am interested in built-in library.
OR
If possible please share implemented example of client/server architecture.

This is for the server:
Thread serverThread = new Thread(new Runnable() {
#Override
public void run() {
try {
serverSocketTCP = new ServerSocket();
serverSocketTCP.setReuseAddress(true);
serverSocketTCP.bind(new InetSocketAddress(YourPort));
while (status) {
clientSocketTCP = serverSocketTCP.accept();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
OutputStream outputStream = client.getOutputStream();
}
} catch (Exception e) {
e.printStackTrace();
}
});
serverThread.start();
This is for the client:
Socket clientSocket = new Socket(ServerIP,ServerPort);
outputStream = clientSocket.getOutputStream();
bufferedReader=newBufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

Make the device that starts the game run as a TCP server and make it broadcast on the network and listen on a predetermined port. When another player wants to join, he just selects the server from a menu and join the game. The coordinates can be sent as packets on touch events.

Related

Connection between Android and C# application

I'm trying to send a simple string between Android device and a C# application
on android as client
Thread thread = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("192.168.1.136",80);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
on the PC as a server using C#
byte[] byteReadStream = null;
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
TcpListener tcpl = new TcpListener(ipe);
while (true)
{
tcpl.Start();
TcpClient tcpc = tcpl.AcceptTcpClient();
byteReadStream = new byte[tcpc.Available];
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
Console.WriteLine(Encoding.Default.GetString(byteReadStream) + "\n");
}
I have tried using specific IP and port it did not work
Bluetooth did not work
I have tried several posted codes on this site, all did not work. So maybe there this something that I am missing.
Please advice me on how to fix the code or a better way to send a string between android and windows app in any instant way.
After looking around some other posts.The problem was that as long as the USB is connected to the device that I'am using for debugging, it always gives host unreachable, remove the USB and then the code works.
I'am not sure if this was the same problem with Bluetooth.

How to control the printwriter from a separate method?

Im working on building my own GUI program that talks to my pc from a tablet. I have the server side done in java but my problem is on the client side.
I want to send data out the PrintWriter to the server from a separate method.
I have accomplished sending in the code below (it sends 'a') but i cant figure out how to send it from a separate method. i believe its a basic java scope problem that im not understanding. i would really appreciate the help.
I have tried moving the variables into other scopes.
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) {
String hostName = "192.168.0.3";
int portNumber = 6666;
try ( //Connect to server on chosen port.
Socket connectedSocket = new Socket(hostName, portNumber);
//Create a printWriter so send data to server.
PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
//Send data to server.
dataOut.println("a");
}catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
public static void sendToServer() {
//I want to control the print writer from this method.
//I have failed i all the ways i have tried.
}
}
You could move the Printer-Code (try try block) into the sendToServer-method and call it via
TestClient client = new TestClient();
client.sendToServer("this is a test");
Of course the sendToServer method needs to accept a parameter then. Even better would probably be to put the main method into a Starter class and decouple it from the Client-Class that you use for sending the data.

Connecting arduino to an android app which uses libgdx (using Bluetooth)

so i'm trying to do something a little unusual, it's just for fun. I have a game i created using libgdx, it consists of a ship that can shoot. What i want to do is to use some external push buttons to move it. The push buttons send signals to arduino, which in turn sends them to an HC-05 bluetooth module. however i'm very doubtful about the android side of things. What i did basically was the following:
Because i'm working on libgdx i created an interface called BluetoothDude, with three methods setBluetooth() (which will set the bluetooth for the particular platform),String whatIsTheMessage() (which will tell you what's been sent to the phone), and boolean isActive(), to know if the bluetooth is active of course.
The MainGame will receive a BluetoothDude so that particular classes like Ship have access to the Message and are able to react to it.
Then i did the particular implementation of Bluetooth for android, in the setBluetooth() i followed this guide very closely: https://developer.android.com/guide/topics/connectivity/bluetooth.html
i'm sure it is connecting properly, because when it creates the socket it can print "connection success with HC-05" (it will only print that if the method which creates the sockets, which i called BTConnect() returns true).
The problem seems to be in reading the data, the code i'm using is
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Handler handler;
public ConnectedThread(BluetoothSocket socket,Handler mHandler) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
handler = mHandler;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
i made an object of this class in setBluetooth like this
if (device != null) {
if (BTconnect()) {
isActive = true;
connectedThread = new ConnectedThread(socket,handler);
System.out.println("connection success with" + device.getName() + " message: " + message );
}
i have a lot of doubts
first what is the target here, the mHandler was created in BluetoothDude, so is that the target?, second i'm quite sure the thread isn't even running because if i put a line like System.out.println("run") inside run() it doesn't show me the line like a trillion times in the logcat when the app is executed. What is wrong with it, i hope you can help me, i'm not very experienced at all of this, and it's driving me crazy.
I cannot see if this is the case from your code but if you are calling platform specific methods, that should be done in the platform specific project subproject.
For more information on how to do that you can check out this page :
https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
So if your LibGDX game has a function say, "setBluetooth" each platform will have its own implementation of said method. That will differ when you compile for Android or iOS.
If you try to call platform specific code in your core game probably won't work.
Hope it helps, maybe you have already done that in which case you can ignore my comment.

Reading Data from Bluetooth Data Transfer on Android

I am looking to get/read the Data I passed after I connected a couple of Android Devices, so far I pair, connect and transmit the information between them, but not sure how to implement the reading part, here I am not sure if I should use createRfcommSocketToServiceRecord or listenUsingRfcommWithServiceRecord to create the reading socket for this purpose.
I have two screens, one where the user push a button and transmit the info and the other where the receiver press another button and read the data, I wonder if the sync is incorrect and after I push the "send" button and then the "read" button the connection is unavailable or if this implementation is just not recomendable all together.
These are my two attempts:
Attempt 1:
//Executed after the user press the read data button
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(device.getName(),uuid);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
BluetoothSocket clientSocket = serverSocket.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
Attempt 2:
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
//clientSocket without method and invoke is not working either
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
On serverSocket.accept() or clientSocket.connect() I get the exception:
Connection is not created, failed or aborted
I would appreciate if anyone could guide me towards getting the data reading part working. Thanks.
Take a look at Android's BluetoothChat example included with the Android SDK. I think it does exactly what you want.
$ANDROID_SDK/samples/android-19/legacy/BluetoothChat/src/com/example/android/BluetoothChat
Read the managing the connection part.
Its clearly written in the documentation how to exchange (read/write) info between devices through Bluetooth. http://developer.android.com/guide/topics/connectivity/bluetooth.html

Create listener for server socket response?

I have a server-client pair and I want to create a listener on the client end for new server responses. I am not sure how to do this, right now I can only interact in a direct synchronous way.
Here is the server:
public class TestServer {
public static void main(String[] args) throws Exception {
TestServer myServer = new TestServer();
myServer.run();
}
private void run() throws Exception {
ServerSocket mySS = new ServerSocket(4443);
while(true) {
Socket SS_accept = mySS.accept();
BufferedReader myBR = new BufferedReader(new InputStreamReader(SS_accept.getInputStream()));
String temp = myBR.readLine();
System.out.println(temp);
if (temp!=null) {
PrintStream serverPS = new PrintStream(SS_accept.getOutputStream());
serverPS.println("Response received: " + temp);
}
}
}
}
As you can see, it sends a response when it gets one. However in general I won't be sure when other servers I use send responses, so I would like to create an asynchronous listener (or at least poll the server for a response every half-second or so).
Here is what I'm trying on the client end:
protected static String getServerResponse() throws IOException {
String temp;
try {
BufferedReader clientBR = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
temp = clientBR.readLine();
} catch (Exception e) {
temp = e.toString();
}
return temp;
}
And just for reference, yes, sending over data from client to server works fine (it System.out's the data correctly). However, when I call the above function to try and retrieve the server response, it just hangs my application, which is an Android application in case that's relevant.
What I want from a function is just the ability to ask the server if it has data for me and get it, and if not, then don't crash my damn app.
On the client side create a ConnectionManager class which will handle all the socket I/O. The ConnectionManager's connect() method will create and start a new thread which will listen for server responses. As soon as it will receive a response it will notify all the ConnectionManager's registered listeners. So in order to receive asynchronously the server responses you will have to register a listener in ConnectionManager using its register(SomeListener) method.
Also, you can have a look at JBoss Netty which is an asynchronous event-driven network application framework. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.

Categories

Resources