Ben Tubul
Ben Tubul

Reputation: 45

C# server and Android Client

I'm working on two programs, one software Microsoft visual studio 2010 when I run a server and a second program : Eclipse ADT (ANDROID device development environment) in which I supposedly client. The goal is to establish a connection between SERVER in C# and Android CLIENT. It should not be a problem, I tried on TCP and UDP tried on, it falls on both object creation context (in TCP that falls on the object socket and UDP SOCKET falls DATAGRAM object creation), it seems to me the problem is: activitythread.performlaunchactivity (activitythread $ activityclientreco rd intent) line 2247

As I understand the problem is not in my code snippet but the SOCKET supplementation with software built into Eclipse, I tried to re-install, add the latest plugin. To your next question, I did permissions for Android device and internet. This I have no idea how to approach this problem which I am going for a month or more ..

In addition I'll add my code in android client :

   import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream;
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader;
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 

import android.util.Log; 

public class MainActivity extends Activity { 
private TextView txt;
private Button b;

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    b = (Button)findViewById(R.id.button1);
    txt = (TextView)findViewById(R.id.textView1);


    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        connectSocket("Hello");

        }
    });
} 

private void connectSocket(String a){ 

    try { 
        InetAddress serverAddr = InetAddress.getByName("10.0.0.8"); 
        Log.d("TCP", "C: Connecting..."); 
        **Socket socket = new Socket(serverAddr, 4444);** 

        String message = "1";

        PrintWriter out = null;
        BufferedReader in = null;

        try { 
            Log.d("TCP", "C: Sending: '" + message + "'"); 
            out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                

            out.println(message);
            while ((in.readLine()) != null) {
                txt.append(in.readLine());
            }

            Log.d("TCP", "C: Sent."); 
            Log.d("TCP", "C: Done.");               

        } catch(Exception e) { 
            Log.e("TCP", "S: Error", e); 
        } finally { 
            socket.close(); 
        } 

    } catch (UnknownHostException e) { 
        // TODO Auto-generated catch block 
        Log.e("TCP", "C: UnknownHostException", e); 
        e.printStackTrace(); 
    } catch (IOException e) { 
        // TODO Auto-generated catch block 
        Log.e("TCP", "C: IOException", e); 
        e.printStackTrace(); 
    }       
} 
} 

and my server in C# :

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

public class TestTCP
{
    public static void Main()
    {
        try
        {
            IPAddress ipAd = IPAddress.Parse("127.0.0.1");
            // use local m/c IP address, and 

            // use the same in the client


            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, 11000);

            /* Start Listeneting at the specified port */
            myList.Start();

            Console.WriteLine("The server is running at port 11000...");
            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");
        m:
            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);

            char cc = ' ';
            string test = null;
            Console.WriteLine("Recieved...");
            for (int i = 0; i < k - 1; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                cc = Convert.ToChar(b[i]);
                test += cc.ToString();
            }

            switch (test)
            {
                case "1":
                    break;


            }

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");


            /* clean up */
            goto m;
            s.Close();
            myList.Stop();
            Console.ReadLine();

        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }

}

Thanks.

Upvotes: 0

Views: 4447

Answers (1)

Gooseman
Gooseman

Reputation: 2231

First of all you may not run the connecSocket method in your UI thread. You have to do something like this:

b.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Thread stackOverflow = new Thread(new Runnable() {

           @Override
           public void run() {
               connectSocket("Hello");

           }});

        stackOverflow.start();
    }
});

Otherwise you get this exception:

android.os.NetworkOnMainThreadException

Secondly you must connect to the same port and interface where your server is listening:

IPAddress ipAd = IPAddress.Parse("127.0.0.1");

Should be the same address as the one you are using in your Android application:

IPAddress ipAd = IPAddress.Parse("10.0.0.8");

And your Android application must connect to the same port where server is listening:

Socket socket = new Socket(serverAddr, 11000);

Finally do not forget the Android permissions:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And be careful with firewalls and things like that, they could also drop your connections.

Upvotes: 1

Related Questions