Server Client Application with .NET and Xamarin

南楼画角 提交于 2019-11-28 10:10:02

On Xamarin.Android you can use all of the regular .Net socket classes:

Namespaces:

using System.Net;
using System.Net.Sockets;

Example:

IPHostEntry ipHostInfo = Dns.GetHostEntry (Dns.GetHostName ());
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 11000);
System.Diagnostics.Debug.WriteLine(ipAddress.ToString());
// Create a TCP/IP socket.
Socket listener = new Socket (AddressFamily.InterNetwork,
                     SocketType.Stream, ProtocolType.Tcp);

AndroidManifest.xml Required Permissions are:

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

The MSDN-based Asynchronous Server Socket example works as a cut/paste example with no changes.

i.e.

Using the MSDN code, you can call the static method, AsynchronousSocketListener.StartListening, in a thread to start listening on port 11000 defined in the AsynchronousSocketListener class.

new Thread (new ThreadStart (delegate {
    AsynchronousSocketListener.StartListening();
})).Start ();

Once it is running on your device/emulator, you can telnet into your Android TCP socket server:


>telnet 10.71.34.100 11000

Trying 10.71.34.100...
Connected to 10.71.34.100.
Escape character is '^]'.

Once connected, type in This is a test<EOF> and the Android will echo it back:

This is a test<EOF>

You do this like in normal .net, except you have to ask permissions to use sockets.

There are tons of simple example of creating a listening tcp connection in c#.

The problem you will have is to know the IP address of your server (in the phone) as it will likely change often when the user is moving.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!