Socket Programming

General topics about the Android-Platform itself.
Coding issues please to the subforum right below.

Socket Programming

Postby Sagar Ganeshe » Wed Dec 19, 2007 12:00 pm

Hi, 8)

Can anyone put some light on how to estblish a Client - Server connection.
I am tryign to use Socket class, but I am not able to get all the functionalities like Listen() and Accept().
Please tell me, which class shall I use?

Thnx... :)
Sagar Ganeshe
Freshman
Freshman
 
Posts: 9
Joined: Mon Dec 10, 2007 6:43 am

Top

Postby plusminus » Wed Dec 19, 2007 6:42 pm

Hello Sagar Ganeshe,

Do you need TCP or UDP-Connections (UDP-Example is :src: here )

Probably TCP as you asked for accept(). No TCP tutorials yet, but when there is some 'free' time, also there are said to be problems doing TCP, so far.

I'll have a look.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Sagar Ganeshe » Thu Dec 20, 2007 11:56 am

Dear Plus Minus,

Thanks for reply, yes I am trying for TCP.
But I am getting an exception, when I am creating the socket in client side.
Using Socket(String dstName, int dstPort) API.
Can you give some suggestions on this..


Regards..
Sagar :D
Sagar Ganeshe
Freshman
Freshman
 
Posts: 9
Joined: Mon Dec 10, 2007 6:43 am

Postby daroN » Thu Dec 20, 2007 12:52 pm

Hi Sagar,

try something like this on the client-side

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. try
  3.  
  4. {
  5.  
  6.      /* open socket */
  7.  
  8.      Socket connfd = new Socket (hostAddr, servPort);
  9.  
  10.      InputStream in = connfd.getInputStream ();
  11.  
  12.      OutputStream out = connfd.getOutputStream ();
  13.  
  14.      BufferedReader con = new BufferedReader (new InputStreamReader (System.in));
  15.  
  16.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


You`r able to read from the Socket with in.read() und write just to it with out.write().

I hope this is a little help :)

greetz,
daroN
daroN
Junior Developer
Junior Developer
 
Posts: 15
Joined: Fri Dec 14, 2007 7:58 pm

Postby plusminus » Thu Dec 20, 2007 4:39 pm

Hey guys,

please report if you had success doing TCP-Communication :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Sagar Ganeshe » Thu Dec 27, 2007 6:46 am

Hi,

Please see the code snippet for Android Server and Client.
With this code I am not able to establish the connection. :(

ANDROID SERVER:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. try {
  2.  
  3.         sSocket = new ServerSocket(port);//,1,InetAddress.getByName("172.28.5.71"));
  4.  
  5.         //sSocket.bind(sSocket.getLocalSocketAddress());
  6.  
  7.         boolean listening = true;
  8.  
  9.         while(listening) {
  10.  
  11.                  if (sSocket == null) {
  12.  
  13.                         sSocket = new ServerSocket(port);
  14.  
  15.                         //sSocket = new ServerSocket(port,1,InetAddress.getByName("172.28.5.71"));
  16.  
  17.                  }
  18.  
  19.                  Socket sock = sSocket.accept();
  20.  
  21.                  new Thread((Runnable) sock).start();
  22.  
  23.  
  24.  
  25.                  if(sock!=null){
  26.  
  27.                                 NotificationManager nm = (NotificationManager)
  28.  
  29.                         getSystemService(NOTIFICATION_SERVICE);
  30.  
  31.                         nm.notifyWithText(R.id.Start_button,
  32.  
  33.                         getText(R.string.short_notification_text),
  34.  
  35.                         NotificationManager.LENGTH_SHORT, null);
  36.  
  37.                  }
  38.  
  39.         }                              
  40.  
  41.         } catch (UnknownHostException e) {                                             
  42.  
  43.                         e.printStackTrace();
  44.  
  45.         } catch (IOException e) {                              
  46.  
  47.                 e.printStackTrace();
  48.  
  49.         }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


ANDROID CLIENT:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. try {
  2.  
  3.             kkSocket = new Socket(ipAddress, port);
  4.  
  5.  
  6.  
  7. } catch (UnknownHostException e) {
  8.  
  9.             errorMessage("Unknown host" + ipAddress);
  10.  
  11.  
  12.  
  13. } catch (IOException e) {
  14.  
  15.             errorMessage("Couldn't get I/O for the connection to: " + ipAddress);
  16.  
  17.  
  18.  
  19. }  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


I am getting the Exception : "Couldn't get I/O for the connection to: 172.28.5.71"
:x

Please provide some help on this.
Sagar Ganeshe
Freshman
Freshman
 
Posts: 9
Joined: Mon Dec 10, 2007 6:43 am

Top

Postby daroN » Thu Dec 27, 2007 11:12 am

With this exception,...hmm try it with Input- and OutputStreams!
For the Streams and the Connection try it with an internal class which extends the Thread-class like this

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. ...
  3.  
  4. class Connection extends Thread {
  5.  
  6.         DataInputStream in;
  7.  
  8.         DataOutputStream out;
  9.  
  10.         Socket clientSocket;
  11.  
  12.         public Connection (Socket aClientSocket) {
  13.  
  14.                 try {
  15.  
  16.                         clientSocket = aClientSocket;
  17.  
  18.                         in = new DataInputStream( clientSocket.getInputStream());
  19.  
  20.                         out =new DataOutputStream( clientSocket.getOutputStream());
  21.  
  22.                         this.start();
  23.  
  24.                 } catch(IOException e) {e.printStackTrace();}
  25.  
  26.         }
  27.  
  28.         public void run(){
  29.  
  30.                 try {                                    // an echo server
  31.  
  32.  
  33.  
  34.                         String data = in.readUTF();                       // read a line of data from the stream
  35.  
  36.                         out.writeUTF(data);
  37.  
  38.                 }catch(IOException e) {e.printStackTrace();
  39.  
  40.                 } finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}
  41.  
  42.                
  43.  
  44.  
  45.  
  46.         }
  47.  
  48. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4
daroN
Junior Developer
Junior Developer
 
Posts: 15
Joined: Fri Dec 14, 2007 7:58 pm

Postby Sagar Ganeshe » Thu Dec 27, 2007 1:23 pm

Hi,

Thnx for replying , but the issue is when I am creating the socket on the clisnt side using
kkSocket = new Socket(ipAddress, port); the exception is thrown.

The streams i can use only when the connection is establised between the Client and Server.
Correct me if I am wrong ? :?

Thanks once again for replying :)
Sagar Ganeshe
Freshman
Freshman
 
Posts: 9
Joined: Mon Dec 10, 2007 6:43 am

Postby daroN » Thu Dec 27, 2007 1:35 pm

Your welcome!
Just for testing use localhost (127.0.0.1) as the ipAdress for the client, would be interesting if the exception is also thrown...

let us know :)
daroN
Junior Developer
Junior Developer
 
Posts: 15
Joined: Fri Dec 14, 2007 7:58 pm

Postby Sagar Ganeshe » Thu Dec 27, 2007 1:41 pm

Yes I am getting the same exception with the IP address as 127.0.0.1 :)
Do you have any suggestions , let me know :(
Sagar Ganeshe
Freshman
Freshman
 
Posts: 9
Joined: Mon Dec 10, 2007 6:43 am

Postby qamerfarooq » Tue Jan 15, 2008 8:32 am

plusminus wrote:Hey guys,

please report if you had success doing TCP-Communication :)

Regards,
plusminus


I have changed the UDP Exampe to TCP, and following code successfully executed for TCP-Communication.



SocketTest.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class SocketTest extends Activity {
  3.  
  4.     /** Called when the activity is first created. */
  5.  
  6.     @Override
  7.  
  8.     public void onCreate(Bundle icicle) {
  9.  
  10.         super.onCreate(icicle);
  11.  
  12.         setContentView(R.layout.main);
  13.  
  14.        
  15.  
  16.         Thread sThread = new Thread(new TCPServer());
  17.  
  18.         Thread cThread = new Thread(new TCPClient());
  19.  
  20.        
  21.  
  22.         sThread.start();
  23.  
  24.         try {
  25.  
  26.                Thread.sleep(1000);
  27.  
  28.           } catch (InterruptedException e) { }
  29.  
  30.        
  31.  
  32.           cThread.start();
  33.  
  34.     }
  35.  
  36. }
  37.  
  38.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


TCPServer.java

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class TCPServer implements Runnable{
  3.  
  4.        
  5.  
  6.     public static final String SERVERIP = "127.0.0.1";
  7.  
  8.     public static final int SERVERPORT = 4444;
  9.  
  10.          
  11.  
  12.     public void run() {
  13.  
  14.          try {
  15.  
  16.               Log.d("TCP", "S: Connecting...");
  17.  
  18.              
  19.  
  20.               ServerSocket serverSocket = new ServerSocket(SERVERPORT);
  21.  
  22.               while (true) {
  23.  
  24.                   Socket client = serverSocket.accept();
  25.  
  26.                   Log.d("TCP", "S: Receiving...");
  27.  
  28.                   try {
  29.  
  30.                       BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  31.  
  32.                       String str = in.readLine();
  33.  
  34.                       Log.d("TCP", "S: Received: '" + str + "'");
  35.  
  36.                     } catch(Exception e) {
  37.  
  38.                         Log.e("TCP", "S: Error", e);
  39.  
  40.                     } finally {
  41.  
  42.                         client.close();
  43.  
  44.                         Log.d("TCP", "S: Done.");
  45.  
  46.                     }
  47.  
  48.  
  49.  
  50.               }
  51.  
  52.              
  53.  
  54.          } catch (Exception e) {
  55.  
  56.                  Log.e("TCP", "S: Error", e);
  57.  
  58.          }
  59.  
  60.     }
  61.  
  62. }
  63.  
  64.  
Parsed in 0.042 seconds, using GeSHi 1.0.8.4


TCPClient.java

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class TCPClient implements Runnable {
  3.  
  4.  
  5.  
  6.        
  7.  
  8.     public void run() {
  9.  
  10.          try {
  11.  
  12.                  
  13.  
  14.                  InetAddress serverAddr = InetAddress.getByName(UDPServer.SERVERIP);
  15.  
  16.                  
  17.  
  18.                  Log.d("TCP", "C: Connecting...");
  19.  
  20.                  Socket socket = new Socket(serverAddr, TCPServer.SERVERPORT);
  21.  
  22.                  String message = "Hello from Client";
  23.  
  24.                      try {
  25.  
  26.                          Log.d("TCP", "C: Sending: '" + message + "'");
  27.  
  28.                          PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
  29.  
  30.                          
  31.  
  32.                          out.println(message);
  33.  
  34.                          Log.d("TCP", "C: Sent.");
  35.  
  36.                      Log.d("TCP", "C: Done.");
  37.  
  38.                          
  39.  
  40.              } catch(Exception e) {
  41.  
  42.                  Log.e("TCP", "S: Error", e);
  43.  
  44.                       } finally {
  45.  
  46.                         socket.close();
  47.  
  48.                       }
  49.  
  50.          } catch (Exception e) {
  51.  
  52.               Log.e("TCP", "C: Error", e);
  53.  
  54.          }
  55.  
  56.     }
  57.  
  58. }
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


AndroidManifest.xml

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.    package="com.e2esp.socket.test">
  7.  
  8.     <application android:icon="@drawable/icon">
  9.  
  10.         <activity class=".SocketTest" android:label="@string/app_name">
  11.  
  12.             <intent-filter>
  13.  
  14.                 <action android:value="android.intent.action.MAIN" />
  15.  
  16.                 <category android:value="android.intent.category.LAUNCHER" />
  17.  
  18.             </intent-filter>
  19.  
  20.         </activity>
  21.  
  22.     </application>
  23.  
  24. </manifest>
  25.  
  26.  
Parsed in 0.003 seconds, using GeSHi 1.0.8.4
qamerfarooq
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Jan 11, 2008 6:07 am
Location: Pakistan

Postby plusminus » Wed Jan 16, 2008 12:42 am

Hello qamerfarooq,

thx for your contribution. :)

Could you approve your code also from emulator to another PC :?:

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby qamerfarooq » Wed Jan 16, 2008 6:03 am

plusminus wrote:Hello qamerfarooq,

thx for your contribution. :)

Could you approve your code also from emulator to another PC :?:

Regards,
plusminus


Yes i successfully executed it with my Desktop PC as Server and Android Client.

I made few changes (like replacing android logging with system.out etc.) in the TCPServer.java and executed it on my PC and successfully communicated with my desktop PC using TCPClient running on the emulator (after pointing the TCPClient to the desktop computer's IP).

Check the attached Files.
Attachments
SocketTest.zip
(1.62 KiB) Downloaded 4691 times
qamerfarooq
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Jan 11, 2008 6:07 am
Location: Pakistan

Postby qamerfarooq » Wed Jan 16, 2008 6:51 am

I have a question, currently we are communicating using hard coded IP addresses, but in the real world this is not the case i think. You come across any mobile and start communicating/sharing etc without having any prior knowledge of other person's IP (desktop/ android phone) etc.

So what is the solution to this issue ? If some one has any idea plz share it?.
qamerfarooq
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Jan 11, 2008 6:07 am
Location: Pakistan

Postby aBin » Wed Jan 16, 2008 1:51 pm

I implement JNI TCP socket and compile and pull the client C library
into andoird playing as client which called by java class. At the same
time, i use PC playing as server.
I set the port 3333 as conncecting TCP PORT.
suppose my PC IP is 192.168.52.34.
My question is how can i set the server and client's listening IP
address?
1) ---------------------------------------------------------
server IP address: 127.0.0.1
client IP address: 192.168.52.34
2) ---------------------------------------------------------
server IP address: 127.0.0.1
client IP address: 127.0.0.1
3) ---------------------------------------------------------
server IP address: 192.168.52.34
client IP address: 192.168.52.34
4) ---------------------------------------------------------
server IP address: 192.168.52.34
client IP address: 127.0.0.1
---------------------------------------------------------
which one should I choose?

qamerfarooq wrote:
plusminus wrote:Hello qamerfarooq,

thx for your contribution. :)

Could you approve your code also from emulator to another PC :?:

Regards,
plusminus


Yes i successfully executed it with my Desktop PC as Server and Android Client.

I made few changes (like replacing android logging with system.out etc.) in the TCPServer.java and executed it on my PC and successfully communicated with my desktop PC using TCPClient running on the emulator (after pointing the TCPClient to the desktop computer's IP).

Check the attached Files.
aBin
Freshman
Freshman
 
Posts: 2
Joined: Tue Nov 27, 2007 5:59 am

Top
Next

Return to General

Who is online

Users browsing this forum: No registered users and 7 guests