Connection between Android and C# application - java

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.

Related

Android App can't connect with Java Server via Socket

I m trying to create a simple test application that connect via Socket to my computer (in localhost).But it thows some exception and I can't figure out how to solve it. NOTE: I m running the apk in my phone (not in an emulator)
Java Server Code
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run(){
System.out.println("Server is running and listening ... ");
try{
ServerSocket ss = new ServerSocket(7000);
while(true){
Socket s = ss.accept();
System.out.println("Connesso");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from Client: "+ dis.readUTF());
dis.close();
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
};
t.start();
}
}
And this is the
Andorid Client Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button sendBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBTN=(Button)findViewById(R.id.button);
sendBTN.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run(){
try {
System.out.println("Starting Connection");
Socket s = new Socket("127.0.0.1", 7000);
System.out.println("Connection DONE");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Let's Test The Socket");
dos.flush();
dos.close();
s.close();
System.out.println("Closing socket");
} catch (UnknownHostException e){
System.out.println("There was an Unknown Erorr:");
e.printStackTrace();
} catch (IOException e) {
System.out.println("There was an IOException:");
e.printStackTrace();
}
}
};
t.start();
Toast.makeText(this, "Messagge Sent...", Toast.LENGTH_SHORT).show();
}
}
What I get it this error:
I also tried some other ports like 1432 or 8000 or 8080 but the result is the same
Then I tried to change the IP from 127.0.0.1 to my own PC ip.. and what I get is this error..
EDIT:
I tried to run the app inside an Emulator using 10.0.2.2 as IP and everything woks fine.. I also tried to use my Private Ip in another JAVA Client program and it works fine.. So the problem is just the connection beetween my real phone and my PC (even if they are in the same network)
Make sure the IP when set to use your local machine from the emulator is 10.0.2.2
When you are using your phone and your PC:
If you are on the same network, make sure you're using the appropriate IP for your PC on your network as the server connection host. I usually set my physical machines to static IPs on my network (through my router) so I don't have to constantly look at what they are, but this is by no means a requirement.
If you are using your phone off of your home network, you will have to use the IP your ISP gives to connect, and make sure that the port is forwarded appropriately in your router if you have one set up.
In either case, you'll need to make sure the firewall is allowing incoming connections on the port you are specifying.
Ok I found the solution.
Then I deleted the exception I ve made in my firewall for port 7000 and I created a new exception which allow the connection using port 3000 and now it works fine.
If you're trying to connect the localhost listening server via Android Virtual Device, you must first check whether the "mobile data" in the AVD is in "On" state, since it doesn't work if it is in "Off" state, well I don't know the exact reason but it works like that.

Implementing xml rpc server on Android

I'm developing an app to exchange data between an Android phone and a pc. I've chosen xml-rpc as a way to communicate, and as a library i downloaded android-xmlrpc (https://code.google.com/p/android-xmlrpc/).
When I call remote procedures from my phone, I use the XMLRPCClient and it works almost fine.
But then I have to synchronize data from my server to the application, so I need to listen on a given port and wait for a xmlrpc request.
I tried the following code:
protected Void doInBackground(Void... params) {
try { ServerSocket socket = new ServerSocket(8888);
XMLRPCServer server = new XMLRPCServer();
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
}
} catch (Exception e) { Log.v(LOG_TAG, "Server: Error", e); }
return null;
}
But it seems it never receives any procedure call. I mean, to debug it I'm trying to use my XMLRPCClient as follow:
XMLRPCClient client = new XMLRPCClient("http://127.0.0.1:8888/");
Object o = client.call("add",1,3);
Log.v(LOG_TAG, o.toString());
And I always get no response. It's stuck on readMethodCall and never reads that the method I requested is "add"... It's strange it gets stuck there. Can't figure the reason why it is stucked here. Do you have any idea ?

Usage of WiFi-Direct in Game Development (Android)

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.

Client-Server Program, can connect from Java client but not from Android

I have a working Java client/server program which is very straightforward and basic. This works fine. However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. I am using almost identical code for the android networking code as I use for the normal client. My android code is simple, all it does is starts this thread from onCreate:
private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;
private Thread clientThread = new Thread("ClientThread") {
#Override
public void run() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
DataInputStream din = new DataInputStream( socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
while (true) {
String message = din.readUTF();
setPicture("picture1");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). When I run my normal pc client with the same port and IP address, the connection goes through. But when I run this code on my android device, the socket timesout when I try to connect.
Does anyone have any suggestions for where I am going wrong?
Double check that you added the permission requirement in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
But, possibly more importantly, 192.168.x.x is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? If you're on mobile, try it from wifi.

Server not receiving message from client with correct IP and port opened

What can cause this to happen?
I moved my laptop to a friends house to work on this project. I opened the same port on his xfinity router, and changed all areas of my code to his IP. However it appears that the client is sending a message and the server has never getting past this part of code
System.out.println("running server!");
int nreq = 1;
try{
//SET ME PORT
ServerSocket sock = new ServerSocket(7332);
for(;;){
Socket newsock = sock.accept();
System.out.println("Creating thread...");
//Broken Old Login crap, needs reworked for map n stuff anyhow now
// Thread t = new ThreadHandler(newsock, nreq);
Thread t = new RequestInterpreter(newsock, nreq);
//t.run();
t.start();
nreq++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
It never gets to print "Creating thread". I'm not sure where to begin with what could be going wrong here?
The only thing that has changed is the house, IP, router, and internet. Works everywhere else. What about those changing could block the client from sending a
Here is a test client I wrote also.
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class testClientConnection {
public static void main(String[] args) {
System.out.println("Starting testConnection");
try{
Socket s = new Socket("xx.xx.xx.xxx", 7332);
DataInputStream fromServer = new DataInputStream(s.getInputStream());
PrintWriter toServer = new PrintWriter(s.getOutputStream(), true);
toServer.println("account name");
toServer.println("password");
toServer.println("Login");
System.out.println("Sent message...");
String response = fromServer.readLine().toString();
//Toast the result here? //testing
System.out.println("response: " + response);
if (response.equals("Login Success")) {
System.out.println("Login Success!!!");
}
}
catch(Exception e){ /
}
}
}
HUGE UPDATE!
Ok so my client was an android phone and I turned the wifi off, so it fell onto 4g-LTE. Then it worked. So... Something is blocking the client side code. What might that be?
The firewall on your friend's router is the usual suspect.
Second suspect is the firewall on the target machine.
Try disabling those.
The problem will be NAT on the router.
Servers don't work behind NAT devices unless you set up port-forwarding so that the router knows where to send an incoming request from outside.

Categories

Resources