TCP Sockets

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

Postby asimov1981 » Tue Apr 20, 2010 1:45 pm

Here is some very simple Code for the problem.
for me it works fine, with a Motorola Milestone(Droid)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4. package ServerforSocket;
  5.  
  6.  
  7.  
  8. import java.io.PrintWriter;
  9.  
  10. import java.net.ServerSocket;
  11.  
  12. import java.net.Socket;
  13.  
  14.  
  15.  
  16.  
  17.  
  18. public class ServerforSocket {
  19.  
  20.  
  21.  
  22.         /**
  23.  
  24.          * @param args
  25.  
  26.          */
  27.  
  28.            public static void main(String args[]) {
  29.  
  30.                       String data = "Hallo ich bin ein socket Test";
  31.  
  32.                       try {
  33.  
  34.                    
  35.  
  36.                                  
  37.  
  38.                          ServerSocket srvr = new ServerSocket(1025);
  39.  
  40.                          Socket skt = srvr.accept();
  41.  
  42.                          System.out.print("Server has connected!\n");
  43.  
  44.                          PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
  45.  
  46.                        
  47.  
  48.                          out.print(data);
  49.  
  50.                          out.close();
  51.  
  52.                          skt.close();
  53.  
  54.                          srvr.close();
  55.  
  56.                       }
  57.  
  58.                       catch(Exception e) {
  59.  
  60.                          System.out.print("Whoops! It didn't work!\n");
  61.  
  62.                       }
  63.  
  64.                    }
  65.  
  66. }
  67.  
  68.  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


Android Client:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package com.examples.HelloSocket;
  3.  
  4.  
  5.  
  6. import java.io.BufferedReader;
  7.  
  8. import java.io.InputStreamReader;
  9.  
  10. import java.net.Socket;
  11.  
  12.  
  13.  
  14.  
  15.  
  16. import android.app.Activity;
  17.  
  18. import android.os.Bundle;
  19.  
  20. import android.view.View;
  21.  
  22. import android.widget.Button;
  23.  
  24. import android.widget.EditText;
  25.  
  26. import android.widget.TextView;
  27.  
  28. import android.widget.Toast;
  29.  
  30.  
  31.  
  32. public class HelloSocket extends Activity {
  33.  
  34.     /** Called when the activity is first created. */
  35.  
  36.     @Override
  37.  
  38.     public void onCreate(Bundle savedInstanceState) {
  39.  
  40.         super.onCreate(savedInstanceState);
  41.  
  42.         setContentView(R.layout.main);
  43.  
  44.         /** Called when the activity is first created. */
  45.  
  46.      
  47.  
  48.             final Button ok = (Button) findViewById(R.id.ok);
  49.  
  50.            
  51.  
  52.             final EditText entry = (EditText) findViewById(R.id.entry);
  53.  
  54.             TextView output = (TextView) findViewById(R.id.output);
  55.  
  56.            
  57.  
  58.             ok.setOnClickListener(new View.OnClickListener() {
  59.  
  60.                 public void onClick(View v) {
  61.  
  62.                
  63.  
  64.                     // übergebe IP Adresse
  65.  
  66.                         testSocket ((CharSequence) entry.getText());
  67.  
  68.                        
  69.  
  70.                 }
  71.  
  72.             });
  73.  
  74.  
  75.  
  76.          
  77.  
  78.            
  79.  
  80.         }
  81.  
  82.        
  83.  
  84.         public void testSocket (CharSequence ipNumber){
  85.  
  86.                 try{
  87.  
  88.                         Toast.makeText(HelloSocket.this, "Try to connect to Server " +ipNumber, Toast.LENGTH_SHORT).show();
  89.  
  90.                          Socket skt = new Socket("139.174.101.121",1025);
  91.  
  92.                          BufferedReader input = new BufferedReader(new InputStreamReader(skt.getInputStream()));
  93.  
  94.                          TextView output = (TextView) findViewById(R.id.output);
  95.  
  96.  
  97.  
  98.                          output.setText(input.readLine());
  99.  
  100.         //               Toast.makeText(HelloSocket.this, "And the winner is: " + input.toString(), Toast.LENGTH_SHORT).show();
  101.  
  102.                 }
  103.  
  104.                 catch(Exception e){
  105.  
  106.                         e.printStackTrace();
  107.  
  108.                         String errorMessage = ("Exception: " +e);
  109.  
  110.                         TextView output = (TextView) findViewById(R.id.output);
  111.  
  112.                 output.setText("S: Error"+ e);
  113.  
  114.                         Toast.makeText(HelloSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
  115.  
  116.                        
  117.  
  118.                 }
  119.  
  120.         }
  121.  
  122.     }
  123.  
  124.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


Hope this will help you
asimov1981
Freshman
Freshman
 
Posts: 7
Joined: Wed Feb 24, 2010 10:50 am

Top

Postby Hareide » Wed Apr 28, 2010 2:40 pm

Sockets on the android emulator is such a pain. I've been strugling with it for 2 days now.

It seems that there are 2 main problems:
<uses-permission android:name="android.permission.INTERNET"/>
Must be added to AndroidManifest.xml

If you had a real device instead of the emulator, the pain would go away. This is because they implemented a virtual router between the development computher and the emulator.
http://developer.android.com/guide/deve ... networking

Theres also a "guide" for how you would go about getting 2 emulators interconnect.
http://developer.android.com/guide/deve ... connecting

You should be aware that the emulator has its own loopback (127.0.0.1). You can connect to your development machines loopback through 10.0.2.2.

I find it strange that there seem to be no 'guide' to this problem.
If you haven set up your enviorment, you have to go to: ...\android-sdk-windows\tools to be able to use the commands. This is done in cmd.exe
C:\>adb devices
List of devices attached
emulator-5554 device
emulator-5556 device

C:\>adb -s emulator-5554 forward tcp:44000 tcp:44000

--- Update: Think I got it to work --- Her is my step-by-step guide of how I did it:
C:\>cd C:\Prosjekter

C:\Prosjekter\>android create project --package eksempel.server --activity Server --target android-7 --path C:/Prosjekter/Server
C:\Prosjekter\>android create project --package eksempel.klient --activity Klient --target android-7 --path C:/Prosjekter/Klient

Change AndroidManifest.xml for both project, so that it includes the "uses-permission" tag:
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Change C:/Prosjekter/Server/src/Server.java to:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package eksempel.server;
  3.  
  4.  
  5.  
  6. import java.io.*;
  7.  
  8. import java.net.*;
  9.  
  10. import android.app.Activity;
  11.  
  12. import android.os.Bundle;
  13.  
  14. import android.widget.TextView;
  15.  
  16.  
  17.  
  18. public class Server extends Activity
  19.  
  20. {
  21.  
  22.     /** Called when the activity is first created. */
  23.  
  24.     @Override
  25.  
  26.     public void onCreate(Bundle savedInstanceState)
  27.  
  28.     {
  29.  
  30.         super.onCreate(savedInstanceState);
  31.  
  32.         String res = "FAIL";
  33.  
  34.         try {
  35.  
  36.  
  37.  
  38.                 ServerSocket ss = new ServerSocket(12345);
  39.  
  40.                 Socket s = ss.accept();
  41.  
  42.                 System.out.println("S: Client connected" + s.toString());
  43.  
  44.                 PrintWriter out = new PrintWriter(s.getOutputStream(), true);
  45.  
  46.                 BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
  47.  
  48.                
  49.  
  50.                 res = in.readLine();
  51.  
  52.                 out.println("PONG" + res);
  53.  
  54.                        
  55.  
  56.                 } catch (IOException e) {
  57.  
  58.                         e.printStackTrace();
  59.  
  60.                 }
  61.  
  62.                
  63.  
  64.                 TextView tv = new TextView(this);
  65.  
  66.                 tv.setText("S: " + res);
  67.  
  68.                 setContentView(tv);
  69.  
  70.     }
  71.  
  72.    
  73.  
  74. }
  75.  
  76.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Change C:/Prosjekter/Klient/src/Klient.java to:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package eksempel.klient;
  3.  
  4.  
  5.  
  6. import java.io.*;
  7.  
  8. import java.net.*;
  9.  
  10. import android.app.Activity;
  11.  
  12. import android.os.Bundle;
  13.  
  14. import android.widget.TextView;
  15.  
  16.  
  17.  
  18. public class Klient extends Activity
  19.  
  20. {
  21.  
  22.     /** Called when the activity is first created. */
  23.  
  24.     @Override
  25.  
  26.     public void onCreate(Bundle savedInstanceState)
  27.  
  28.     {
  29.  
  30.         super.onCreate(savedInstanceState);
  31.  
  32.         String res = "FAIL";
  33.  
  34.         try {
  35.  
  36.  
  37.  
  38.                 Socket s = new Socket("10.0.2.2", 12345);
  39.  
  40.                 System.out.println("C: Connected to server" + s.toString());
  41.  
  42.                 PrintWriter out = new PrintWriter(s.getOutputStream(), true);
  43.  
  44.                 BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
  45.  
  46.                
  47.  
  48.                 out.println("PING");
  49.  
  50.                 res = in.readLine();
  51.  
  52.                        
  53.  
  54.                 } catch (IOException e) {
  55.  
  56.                         e.printStackTrace();
  57.  
  58.                 }        
  59.  
  60.        
  61.  
  62.         TextView tv = new TextView(this);
  63.  
  64.         tv.setText("C: " + res);
  65.  
  66.         setContentView(tv);
  67.  
  68.     }
  69.  
  70. }
  71.  
  72.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


Create avd for server and client
C:\Prosjekter\>android create avd --name server --target android-7
C:\Prosjekter\>android create avd --name klient --target android-7

Start avd server and client (this take som time, atleast on my machine)
(non-windows users have to drop the "start" part and create a terminal for each launch of emulators)
C:\Prosjekter\>start emulator -avd server
C:\Prosjekter\>start emulator -avd klient

Build using ant. Most of you might not have and it.
For Eclipseusers without ant:
- Create the projects by: File -> New -> Android Project: "Create project form existing source" and chose "C:\Prosjekter\Server\"
- Specify the the right emulators when you launch the projects. Server first and client last. You may also skip the rest of this "document"

C:\Prosjekter\>cd Server
C:\Prosjekter\Server\>c:\ant\bin\ant.bat debug
C:\Prosjekter\Server\>cd..
C:\Prosjekter\>cd Klient
C:\Prosjekter\Klient\>c:\ant\bin\ant.bat debug
C:\Prosjekter\Klient\>cd..

Look at the gui window, you can see something like "5554:server" and "5556:klient"
C:\Prosjekter\>adb devices
List of devices attached
emulator-5556 device
emulator-5554 device

Forward from localhost to server emulator (emulator-5554 = server)
C:\Prosjekter\>adb -s emulator-5554 forward tcp:12345 tcp:12345

C:\Prosjekter\>adb -s emulator-5554 install C:\Prosjekter\Server\bin\Server-debug.apk
C:\Prosjekter\>adb -s emulator-5556 install C:\Prosjekter\Klient\bin\Klient-debug.apk

On the server-emulator, go to the Server app and start it
On the client-emulator, go to the Klient app and start it

The client sends the string "PING" to the server. The server read the string and replays "PING" + "PONG" to the client.
If all works you should see: "S: PING" on the server and "C: PINGPONG" on the client
If you see "S: FAIL" and/or "C: FAIL" then your out of luck. Make sure you did the portforwarding right, and check your firewall.

Attachments: (a reason to become a member, non-members cant see/access them)
- Beutifull diagram of the relations between network and android emulators
- Klient and Server Eclipse project
Attachments
Server.zip
Eclipse Server Complete Project
(41.89 KiB) Downloaded 242 times
Klient.zip
Eclipse Client Complete Project
(41.82 KiB) Downloaded 264 times
AndrodVirtualRouter.png
This might not be 100%, I just made it for myeself to make senze of it all
AndrodVirtualRouter.png (37.27 KiB) Viewed 4298 times
Last edited by Hareide on Thu Apr 29, 2010 4:36 pm, edited 1 time in total.
Hareide
Freshman
Freshman
 
Posts: 2
Joined: Wed Apr 28, 2010 12:54 pm
Location: Norway

Re: TCP Sockets

Postby Hareide » Thu Apr 29, 2010 10:51 am

hugopicado wrote:Hi.

I can't make TCP sockets work. I'm doing this:

Server side:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.             try {
  2.                 ss = new ServerSocket(4444);
  3.                 sc = ss.accept();
  4.             }
  5.             catch (IOException e) {
  6.                 label.setText("erro1");
  7.             }
  8.            
  9.             label.setText("connected");
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Client side:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.             try {
  2.                 sc = new Socket(myIP,4444);
  3.             }
  4.             catch (IOException e) {
  5.                 label.setText("erro2");
  6.             }
  7.            
  8.             label.setText("connected");
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


I'm working in one machine with two emulators running. myIP is an IP from one of my interfaces since I read somewhere that android has problems with "localhost" and "127.0.0.1".

The server just blocks before I can do anything else.
What am I doing wrong?

Thanks in advance.
Best regards,
Hugo.

Add "<uses-permission android:name="android.permission.INTERNET"/>" to AndroidManifest.xml
Should look something like this:
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Setup forwarding through the "Server"-emulators virtual router:
adb -s emulator-5554 forward tcp:4444 tcp:4444

Change:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. sc = new Socket(myIP,4444);
Parsed in 0.036 seconds, using GeSHi 1.0.8.4

to
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. sc = new Socket(10.0.2.2,4444);
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
Hareide
Freshman
Freshman
 
Posts: 2
Joined: Wed Apr 28, 2010 12:54 pm
Location: Norway

Postby kristu » Sun May 09, 2010 1:27 pm

Hareide wrote:Sockets on the android emulator is such a pain. I've been strugling with it for 2 days now.


hello Hareide!
first of all, thanks for this great stuff, it helped me a lot.

i'm developing a simple TicTacToe game for 2 players to play via network. but i don't know, how to implement the turn-based client-server communication.
i have a Client.java and a Server.java class. should they implement a Runnable interface or what?
i think this, because niether the server, nor the client knows when will the next tcp packet arrive, so they have to watch the sockets continously.

so the question is: how should i implement the Server and the Client class?

thank you, greets kristu

ps: sorry for my bad english
kristu
Freshman
Freshman
 
Posts: 4
Joined: Sat May 08, 2010 8:38 pm

Top
Previous

Return to Networking & Database Problems

Who is online

Users browsing this forum: No registered users and 6 guests