【源碼】c#編寫的安卓用戶端與Windows伺服器程式進行網路通訊,

來源:互聯網
上載者:User

【源碼】c#編寫的安卓用戶端與Windows伺服器程式進行網路通訊,

用c#開發安卓程式 (xamarin.android)系列之三

源碼(包含用戶端與伺服器端所有工程檔案)    資料庫檔案      

為了方便您測試,我臨時搭建了一個伺服器  您可以安裝apk檔案,直接測試  apk檔案  (測試伺服器將會運行至2015年3月1日)

通訊架構為來自英國的NetworkComms2.3.1開源通訊架構    序列化採用Protobuf.net開源架構

用戶端介面如下:

      

伺服器端程式介面:

伺服器搭建在winserver2003 上,基於.net4.0.

資料庫採用sql2005

輸入資料:

資料庫建設完成,開啟VS2010開始,建立相關的工程

建立伺服器端工程

 

下一步:開啟CodeSmith建立“預存程序”,“資料層”代碼,“邏輯層(Business層代碼)”:  

相關CodeSmith模板:

分享我所使用的資料庫架構

使用的CodeSmith為6.5版本:

產生完成後,VS中工程圖:

下一步先構建伺服器代碼 

CREATE PROCEDURE [dbo].Users_SelectOneByUserName @Name nvarchar(200)ASSELECT ID,Name,PassWord FROM [dbo].[Users] WHERE [Name] = @Name資料庫中添加預存程序

DBUsers.CS中添加:

        //添加 根據UserID擷取使用者        public static IDataReader GetOneByUserName(           string name)        {            SqlParameterHelper sph = new SqlParameterHelper(GetReadConnectionString(), "Users_SelectOneByUserName", 1);            sph.DefineSqlParameter("@Name", SqlDbType.NVarChar, 200, ParameterDirection.Input, name);            return sph.ExecuteReader();        }

邏輯層DoUsers中添加:

  public static string Login(string username, string password)        {             using (IDataReader reader = DBUsers.GetOneByUserName(username))            {                string theResult = "登入不成功";                Users theUser = PopulateFromReader(reader);                if (theUser == null)                {                    theResult = "使用者不存在";                }                else if (theUser.PassWord == password)                {                     theResult = "登陸成功";                                     }                else                {                    theResult = "密碼不正確";                                  }                return theResult;            }        }

 伺服器端代碼:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms; using NetworkCommsDotNet; using System.Net;using Mobile.Business;using Mobile.Entity;namespace MobileServer{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {             //伺服器開始監聽用戶端的請求             //開始監聽某T連接埠            IPEndPoint thePoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));            TCPConnection.StartListening(thePoint, false);            button1.Text = "監聽中";            button1.Enabled = false;            //此方法中包含伺服器具體的處理方法。            StartListening();        }        private void StartListening()        {                        //禁用日誌記錄  伺服器端正式使用時,禁用日誌記錄            NetworkComms.DisableLogging();                         //處理登陸請求            NetworkComms.AppendGlobalIncomingPacketHandler<Users>("UserLogin", IncomingLoginRequest);        }        //處理某個具體的請求        private void IncomingLoginRequest(PacketHeader header, Connection connection, Users currentUser)        {            try            {                //從資料庫中擷取返回結果                string resMsg  = DoUsers.Login(currentUser.Name,currentUser.PassWord);                ResMessage contract = new ResMessage();                contract.Message = resMsg;                //把結果返回給用戶端                connection.SendObject("ResLogin", contract);            }            catch (Exception ex)            {            }        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            NetworkComms.Shutdown();            this.Dispose();            this.Close();        }    }}

 

至此,我們已經完成了“建設資料庫”,“建表”,“產生資料庫預存程序“,”資料層代碼“,”邏輯層代碼“,”伺服器端代碼的編寫“。只剩下安卓用戶端的編寫了。

 

藉助xamarin平台,用C#語言開發安卓程式,最大的優勢,個人感覺是可以使用.net平台上眾多優秀的庫類,特別是通過穩定成熟的通訊架構與c#伺服器端進行互動。

 

 

修改 Main.axml檔案,增加幾個文字框給使用者輸入使用者名稱和密碼:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/ConnectButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="串連伺服器" /> <TextView android:id="@+id/tvUseName" android:layout_width="195px" android:layout_height="35px" android:text="使用者名稱:" /> <EditText android:id="@+id/etUserName" android:layout_width="195px" android:layout_height="wrap_content" android:text="" android:textSize="18sp" /> <TextView android:id="@+id/tvPassWord" android:layout_width="195px" android:layout_height="35px" android:text="密碼:" /> <EditText android:id="@+id/etPassWord" android:layout_width="195px" android:layout_height="wrap_content" android:text="" android:textSize="18sp" /> <Button android:id="@+id/MyButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="登陸" /> <ScrollView android:id="@+id/mainTextScroll" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight=".1" android:layout_above="@+id/messageTextInput"> <TextView android:id="@+id/mainText" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="bottom" android:inputType="none" /> </ScrollView></LinearLayout>修改Main.axml檔案using System;using Android.App;using Android.Content;using Android.Runtime;using Android.Views;using Android.Widget;using Android.OS;using NetworkCommsDotNet;using DPSBase;using System.Net;using Mobile.Entity;namespace Mobile.Client{ [Activity(Label = "Mobile.Client", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; //串連資訊對象 public ConnectionInfo connInfo = null; //連線物件 Connection newTcpConnection; //串連伺服器 Button connButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //映射登陸按鈕 Button button = FindViewById<Button>(Resource.Id.MyButton); //登陸按鈕相關的方法 button.Click += loginButton_Click; //映射串連伺服器按鈕 connButton = FindViewById<Button>(Resource.Id.ConnectButton); //串連伺服器按鈕相關方法 connButton.Click += connButton_Click; //TextView 顯示資訊 tvShowMessage = FindViewById<TextView>(Resource.Id.mainText); //映射輸入使用者名稱控制項 etUserName = FindViewById<EditText>(Resource.Id.etUserName); //映射輸入密碼控制項 etPassWord = FindViewById<EditText>(Resource.Id.etPassWord); if (NetConnected()) { AppendMessage("網路狀態:可用"); } else { AppendMessage("無網路,請先設定網路"); } } //串連伺服器相關方法 void connButton_Click(object sender, EventArgs e) { //給串連資訊對象賦值 connInfo = new ConnectionInfo(ServerIP, ServerPort); //如果不成功,會彈出異常資訊 newTcpConnection = TCPConnection.GetConnection(connInfo); connButton.Text = "串連成功"; connButton.Enabled = false; } string ServerIP = "115.28.141.108"; int ServerPort = 3003; //用戶端登陸相關方法 void loginButton_Click(object sender, EventArgs e) { Users theUser = new Users(); theUser.Name = etUserName.Text; theUser.PassWord = etPassWord.Text; ResMessage resMessage = newTcpConnection.SendReceiveObject<ResMessage>("UserLogin", "ResLogin", 5000, theUser); if (resMessage.Message == "登陸成功") AppendMessage("登陸成功"); else //顯示錯誤資訊 AppendMessage(resMessage.Message); } //用於顯示資訊的TextView TextView tvShowMessage; //使用者名稱 EditText etUserName; //密碼 EditText etPassWord; /// <summary> /// 資料序列化器 /// </summary> public DataSerializer Serializer { get; set; } //顯示資訊 public void AppendMessage(string message) { tvShowMessage.Text += System.Environment.NewLine + message; } //判斷當前網路是否可用 private bool NetConnected() { var cm = Context.ConnectivityService; var cmMgr = (Android.Net.ConnectivityManager)GetSystemService(cm); if (cmMgr.GetNetworkInfo(Android.Net.ConnectivityType.Mobile).IsConnected || cmMgr.GetNetworkInfo(Android.Net.ConnectivityType.Wifi).IsConnected) { return true; } else { return false; } } }}MainActivity代碼

 文章先寫到這兒,希望您喜歡

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.