0

I am very new to programming c# in visual studio. I am trying to send a message from an android app (Client side) to a windows app (Server side) using sockets. I don't know if I should be able to do it in the wireless network that I have, or is that even the problem. Also can I pick and use any port number or it has to be a specific number that I have to fetch from somewhere? I will post both my client and server codes, and the output of my server side code. Any help is much appreciated.

Client:

public class MainActivity extends Activity { 
private EditText editTxt;

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
Button b = (Button)findViewById(R.id.button1);
editTxt = (EditText) findViewById(R.id.editText1);
final String str = editTxt.getText().toString();



b.setOnClickListener(new View.OnClickListener() {

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

    }
});
} 

private void connectSocket(String a){ 

new Thread( new Runnable() {
    @Override
    public void run() {

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

            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);

                String text = "";
                String finalText = "";
                while ((text = in.readLine()) != null) {
                    finalText += text;
                    }
                editTxt.setText(finalText);


                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(); 
        }  
    }}).start();
    } 
}

Server:

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

            // use the same in the client


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

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

            Console.WriteLine("The server is running at port 5555...");
            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");
            s.Close();


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

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

}
}

Server Output:

The thread 'vshost.NotifyLoad' (0x21e8) has exited with code 0 (0x0).

The thread '<No Name>' (0x1d04) has exited with code 0 (0x0).

The thread 'vshost.LoadReference' (0x2448) has exited with code 0 (0x0).

'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded     'C:\Projects\Offline\WindowsSocketServer\bin\Debug\WindowsSocketServer.exe', Symbols loaded.
'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded   'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50    a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the     debugger option 'Just My Code' is enabled.

Error.....    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot,     SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at System.Net.Sockets.TcpListener.Start()
   at WindowsSocketServer.serv.Main() in 
C:\Projects\Offline\WindowsSocketServer\Program.cs:line 27

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

The thread 'vshost.RunParkingWindow' (0x1a5c) has exited with code 0 (0x0).

The thread '<No Name>' (0x1ba4) has exited with code 0 (0x0).

The program '[8828] WindowsSocketServer.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

1 Answers1

0

You should be able to get more information from the SocketException as to what the problem is. (Description, error code etc). I'm guessing that it breaking on Bind can simply be explained by port 5555 being already in use by another application (adb perhaps?). Usually only one application can listen on a given port, so try a different one. You can pick any port (< 1024 are reserved ports, but any above that up to 65535 are valid). Just update the client to connect to the new port too.

Mark H
  • 13,471
  • 4
  • 26
  • 45
  • Thanks Mark H, I tried different ports however I am still getting the same error. – user3271572 Feb 24 '14 at 16:02
  • Change your catch to catch a `SocketException` rather than just a regular Exception, and print the Message, (Socket)ErrorCode and any other useful information. There could be a number of reasons why it isn't working and there's not enough information in your question to know. – Mark H Feb 24 '14 at 16:05
  • I did that and the message is "The requested address is not valid in its context." Why could that be? I am also googling it, it seems something to do with the IP address. – user3271572 Feb 24 '14 at 16:23
  • You'll want to listen on your LAN IP address, which can be discovered with `ipconfig`, (or through code with `GetHostEntry(GetHostName)`) or simply listen on `IPAddress.Any`. – Mark H Feb 24 '14 at 16:28
  • Okay, I updated my IP Address, and now I have no errors, however it is only says "waiting for a connection..." I also doubt if it is possible to do this socket connection using wifi. – user3271572 Feb 24 '14 at 16:33
  • It's possible over wifi. Have you updated the IP and port on the android app? (Are you sure you're listening on your LAN IP and not a loopback address, `127.0.0.1`. A LAN IP for a typical router will be in the subnet `192.168.*.*` for example). Otherwise it's most likely a case of Windows firewall blocking incoming connections on the port, for which you'll need to add a rule to allow it, or temporarily disable the firewall. – Mark H Feb 24 '14 at 16:36