Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - Server Client Application with .NET and Xamarin

I searched around the internet a lot of hours but I couldn't find anything that matches my case.

I simply want to implement a Server/Client App with TCP or UDP where my Android App (Xamarin) acts as a server and my .NET application as Client. Since I have not much experience with app development and no experience with Xamarin, I was looking for an example. All I found was this:

http://www.codeproject.com/Articles/340714/Android-How-to-communicate-with-NET-application-vi

First of all this is the opposite way (Server on .NET and Client as App) and additionaly it is for Android Studio so it's hard for me to translate these things into Xamarin without errors.

Please can someone help and give me an example how to realize my issue?

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...