[Source code] c # network communication between Android clients and Windows server programs,
Use c # To develop android (xamarin. android) Series 3
Source code (including all engineering files on the client and server) database files
To facilitate your test, you can install the apk file by setting up a server temporarily and test the apk file directly (the test server will run until March 13, March 1, 2015)
The communication framework uses Protobuf.net open-source framework for serialization of the open-source communication framework NetworkComms2.3.1 from the UK.
The client interface is as follows:
Server-side program interface:
The server is built on winserver2003 Based on. net4.0.
The database uses sql2005
Input data:
After the database is built, start VS2010 and create related projects.
Create a server project
Next: Open CodeSmith to create "Stored Procedures", "data layer" code, and "Business Layer Code )":
Related CodeSmith templates:
Share my database framework
CodeSmith 6.5 is used:
After the generation is complete, the engineering drawing in VS is:
Next, build the server code first.
Create procedure [dbo]. Users_SelectOneByUserName @ Name nvarchar (200) asselect id, Name, PassWord FROM [dbo]. [Users] WHERE [Name] = @ NameAdding a stored procedure to a database
Add the following to DBUsers. CS:
// Add the user public static IDataReader GetOneByUserName (string name) {SqlParameterHelper fe-= new SqlParameterHelper (GetReadConnectionString (), "Users_SelectOneByUserName", 1. defineSqlParameter ("@ Name", SqlDbType. NVarChar, 200, ParameterDirection. input, name); return 7d. executeReader ();}
Add the following to the logic layer DoUsers:
Public static string Login (string username, string password) {using (IDataReader reader = DBUsers. getOneByUserName (username) {string theResult = "Logon Failed"; Users theUser = PopulateFromReader (reader); if (theUser = null) {theResult = "user does not exist ";} else if (theUser. passWord = password) {theResult = "Login successful";} else {theResult = "Incorrect PassWord" ;}return theResult ;}}
Server code:
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 button#click (object sen Der, EventArgs e) {// The server starts listening to client requests // starts listening to a T port IPEndPoint thePoint = new IPEndPoint (IPAddress. parse (txtIP. text), int. parse (txtPort. text); TCPConnection. startListening (thePoint, false); button1.Text = "listener"; button1.Enabled = false; // This method contains the specific server processing method. StartListening ();} private void StartListening () {// disable the log record NetworkComms when the server is properly used. disableLogging (); // process the login request NetworkComms. appendGlobalIncomingPacketHandler <Users> ("UserLogin", IncomingLoginRequest);} // process a specific request private void IncomingLoginRequest (PacketHeader header, Connection connection, Users currentUser) {try {// obtain the returned result string resMsg = DoUsers from the database. login (currentUser. name, currentUser. passWord); ResMessage contract = new ResMessage (); contract. message = resMsg; // return the result to the client connection. sendObject ("ResLogin", contract);} catch (Exception ex) {}} private void form=formclosing (object sender, FormClosingEventArgs e) {NetworkComms. shutdown (); this. dispose (); this. close ();}}}
So far, we have completed "database construction", "Table creation", "database storage process generation", "data layer code", "logic layer code", "Writing server-side code". Only the android client is written.
With the help of the xamarin platform, Android is developed in C #. The biggest advantage is that it is usable. net platform, especially through a stable and mature communication framework to interact with the c # server.
Modify the Main. axml file and add several text boxes to enter the user name and password:
<? 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 = "connect to server"/> <TextView android: id = "@ + id/tvUseName" android: layout_width = "195px" android: layout_height = "35px" android: text = "username:"/> <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 = "Password:"/> <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>Modify Main. axml file 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; // connection information object public ConnectionInfo connInfo = null; // Connection object newTcpConnection; // Connection server Button connButton; protected override void OnCreate (Bundle bundle) {base. onCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource. layout. main); // map the login Button button Button = FindViewById <Button> (Resource. id. myButton); // method related to the login button. click + = loginButton_Click; // map the connection server Button connButton = FindViewById <Button> (Resource. id. connectButton); // connection server button related method connButton. click + = connButton_Click; // TextView display information tvShowMessage = FindViewById <TextView> (Resource. id. mainText); // ing input username control etUserName = FindViewById <EditText> (Resource. id. etUserName); // ing the input password control etPassWord = FindViewById <EditText> (Resource. id. etPassWord); if (NetConnected () {AppendMessage ("network status: available");} else {AppendMessage ("No network, SET network first ");}} // Method for connecting to the server void connButton_Click (object sender, EventArgs e) {// assign connInfo = new ConnectionInfo (ServerIP, ServerPort) to the connection information object; // if the connection fails, newTcpConnection = TCPConnection will pop up. getConnection (connInfo); connButton. text = "connection successful"; 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 // displays the error Message AppendMessage (resMessage. message) ;}// TextView tvShowMessage used to display information; // username EditText etUserName; // password EditText etPassWord; /// <summary> /// data Serializer /// </summary> public DataSerializer Serializer {get; set ;}// display information public void AppendMessage (string message) {tvShowMessage. text + = System. environment. newLine + message;} // determine whether the current network is available private bool NetConnected () {var cm = Context. connectivityService; var cmgr = (Android. net. connectivityManager) GetSystemService (cm); if (cmgr. getNetworkInfo (Android. net. connectivityType. mobile ). isConnected | cmgr. getNetworkInfo (Android. net. connectivityType. wifi ). isConnected) {return true;} else {return false ;}}}}MainActivity code
This article is written here first.