Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Database \ C # mobile side and PC-side data exchange     - Cool Android realization SVG animation (Programming)

- C ++ Supplements - Virtual Function Principle (Programming)

- CentOS 6.4 installation environment to build Scrapy 0.22 (Linux)

- Install DB2 V10 and Data Studio V3 under Linux (Ubuntu) environment (Database)

- MySQL Basic tutorial: About varchar (N) (Database)

- Oracle index visible and hidden (visible / invisible) (Database)

- GRUB how to load Linux kernel (Linux)

- Close and limit unused ports computer server security protection (Linux)

- Make full use of the Raspberry Pi SD card space (Linux)

- iOS custom keyboard emoji expression (Programming)

- Python in os.path Magical (Programming)

- Java environment to build a number of issues (Linux)

- How to manage your to-do list with the Go For It on Ubuntu (Linux)

- How to implement Linux host Telnet SSH password Free (Server)

- Some of the bibliographic management tools to good use on linux (Linux)

- VirtualBox CentOS is configured as a local disk mirroring software source (Linux)

- CentOS 6.6 source compiler GCC upgrade to 4.8.2 (Linux)

- C ++ pointer two third memory model (Programming)

- Ubuntu 14.10 / 14.04 / 12.04 virtual users to install the printing software Boomaga (Linux)

- How to install CentOS CentOS web page (Server)

 
         
  C # mobile side and PC-side data exchange
     
  Add Date : 2017-08-31      
         
         
         
  Small note: for the current function of more and more powerful smart phone, the PC-side support for mobile phone users to synchronize data, backup and restore applications such as protection measures have been in urgent need of improvement. Not only to protect the data, and users want their phone with the PC can be integrated, and integration of remote servers. Users want the operation of the mobile terminal can be transferred to the PC side, the PC side of the big screen for the computer, the completion of the same operation can save a lot of user time. For a powerful mobile phone, nearly 1/2 of the application can be synchronized in the PC side. So the PC-side application planning to the perspective of the system to be treated. At the same time to ensure that the mobile phone and PC side of the mainstream interactive mode should be consistent. Personal point of view: data integration and management of diversification is a trend in the future development. The following study today, today's laboratory mobile and PC-side data exchange and analysis.

1, how to achieve the mobile side and PC-side data interaction?

A: 1, Bluetooth 2, NFC technology 3, infrared 4, Socket.

NFC and Bluetooth similarities and differences:

The same point: are close-range transmission.

Differences: NFC is superior to infrared and Bluetooth transmission. As a consumer-oriented trading mechanism, NFC is faster, more reliable, and much simpler than infrared, and does not have to be strictly aligned to infrared to transmit data. Compared with Bluetooth, NFC for close-range transactions, for the exchange of financial information or sensitive personal information and other important data; Bluetooth can make up for the shortcomings of NFC communication distance, suitable for longer distance data communication. Therefore, NFC and Bluetooth complement each other, co-exist. In fact, the fast and lightweight NFC protocol can be used to boot a Bluetooth pairing process between two devices, facilitating the use of Bluetooth. But to achieve long-distance data transmission it can only use Socket,

The following code analysis:

First on the PC server.cs server

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Net;
Using System.Net.Sockets;
Using System.Threading;

Namespace TcpServer
{
    Class Program
    {
        Public static Socket serverSocket;
        Static Thread threadSend;
        Static Thread sendDataToClient;
        Static int count = 1;
        Static void Main (string [] args)
        {
            // Determine the port number
            Int port = 121;

            // Set the connection IP
            String host = "192.168.1.100";

            // Converts an IP address string to an IP address instance
            IPAddress ip = IPAddress.Parse (host);

            // Represent the network endpoint as an IP address and port number
            IPEndPoint ipe = new IPEndPoint (ip, port);

            // Create the Socket
            // The addressFamily parameter specifies the addressing scheme used by the Socket class
            // The socketType parameter specifies the type of the Socket class
            // protocolType parameter specifies the protocol used by Socket.
            Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // socket is associated with a local endpoint
            Socket.Bind (ipe);
            While (true)
            {
                // Start listening for the port
                Socket.Listen (0);

                Console.WriteLine ( "The service is turned on, please wait ....." + DateTime.Now.ToString () + DateTime.Now.Millisecond.ToString ());

                // Create a new Socket for the newly created connection for the client to establish the connection
                ServerSocket = socket.Accept ();
                Console.WriteLine ( "Connection established ..." + DateTime.Now.ToString () + DateTime.Now.Millisecond.ToString ());
                Console.WriteLine ( "client IP:" + serverSocket.RemoteEndPoint);
                String recStr = string.Empty;
                // Define the buffer to receive the client's data
                Byte [] recbyte = new byte [1024];
                
                ReceiveData ();
    
                SendDataToClient = new Thread (sendData);
                SendDataToClient.Start ();

            }}
        }}

        Public static void sendData ()
        {
          
            While (true)
            {
                Console.WriteLine ( "send to client \ n");
                // The server sends a message back to the client
                String strSend = "Hello Android Client!" + DateTime.Now.Second;
                                Byte [] sendByte = new byte [1024];
                // Convert the sent string to byte []
                SendByte = UTF8Encoding.UTF8.GetBytes (strSend);
                / / Server to send data
              
                ServerSocket.Send (sendByte, sendByte.Length, 0);
                Thread.Sleep (1000);
            }}
        }}

        #region
        /// < summary>
        /// Asynchronous connection
        /// < / summary>
        /// < param name = "ip"> < / param>
        /// < param name = "port"> < / param>
        /// < param name = "clientSocket"> < / param>
        Public static void Connect (IPAddress ip, int port)
        {
            ServerSocket.BeginConnect (ip, port, new AsyncCallback (ConnectCallback), serverSocket);
        }}

        Private static void ConnectCallback (IAsyncResult ar)
        {
            Try
            {
                Socket handler = (Socket) ar.AsyncState;
                Handler.EndConnect (ar);
            }}
            Catch (SocketException ex)
            {
                Throw ex;
            }}
        }}
        /// < summary>
        /// send data
        /// < / summary>
        /// < param name = "data"> < / param>
        Public static void Send (string data)
        {
            //Send(System.Text.Encoding.UTF8.GetBytes(data));
            Send (UTF8Encoding.UTF8.GetBytes (data));
        }}
        /// < summary>
        /// send data
        /// < / summary>
        /// < param name = "byteData"> < / param>
        Private static void Send (byte [] byteData)
        {
            Try
            {
                Int length = byteData.Length;
                Byte [] head = BitConverter.GetBytes (length);
                Byte [] data = new byte [head.Length + byteData.Length];
                Array.Copy (head, data, head.Length);
                Array.Copy (byteData, 0, data, head.Length, byteData.Length);
                ServerSocket.BeginSend (data, 0, data.Length, 0, new AsyncCallback (SendCallback), serverSocket);
            }}
            Catch (SocketException ex)
            {}
        }}

        Private static void SendCallback (IAsyncResult ar)
        {
            Try
            {
                Socket handler = (Socket) ar.AsyncState;
                Handler.EndSend (ar);
            }}
            Catch (SocketException ex)
            {
                Throw ex;
            }}
        }}

        Static byte [] MsgBuffer = new byte [128];

        /// < summary>
        /// Receives the message
        /// < / summary>
        Public static void ReceiveData ()
        {
            If (serverSocket.ReceiveBufferSize> 0)
            {
                ServerSocket.BeginReceive (MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback (ReceiveCallback), null);
            }}
        }}

        Private static void ReceiveCallback (IAsyncResult ar)
        {
            Try
            {
                Int REnd = serverSocket.EndReceive (ar);
                Console.WriteLine ( "Length:" + REnd);
                If (REnd> 0)
                {
                    Byte [] data = new byte [REnd];
                    Array.Copy (MsgBuffer, 0, data, 0, REnd);

                    Int Msglen = data.Length;
                    / / In this data can be processed on-demand

                    ServerSocket.BeginReceive (MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback (ReceiveCallback), null);
                    //Console.WriteLine ( "Receive server-side information: {0}", Encoding.ASCII.GetString (MsgBuffer, 0, Msglen));

                    Console.WriteLine ( "Receive server-side information: {0}", UTF8Encoding.UTF8.GetString (data, 0, Msglen));
                }}
                Else
                {
                    Dispose ();
                }}
            }}
            Catch (SocketException ex)
            {}
        }}

        Private static void dispose ()
        {
            Try
            {
                ServerSocket.Shutdown (SocketShutdown.Both);
                ServerSocket.Close ();
            }}
            Catch (Exception ex)
            {
                Throw ex;
            }}
        }}
        #endregion
    }}
}}

Mobile use Unity3D write the script to hang on the mainCamera, the code is as follows:

Using UnityEngine;
Using System.Collections;
Using System.Net.Sockets;
Using System.Net;
Using System;
Using System.Text;
Using System.IO;

Public class client: MonoBehaviour
{
    Public GUIText text;
    Public GUIText path;
    
    Public static Socket clientSocket;
    // Use this for initialization
    Void Start ()
    {
// Server IP
        String LocalIP = "192.168.1.100";
//The port number
        Int port = 121;
        IPAddress ip = IPAddress.Parse (LocalIP);
        IPEndPoint ipe = new IPEndPoint (ip, port);
        ClientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / create a client Socket
        ClientSocket.Connect (ipe);

        StartCoroutine ( "sendData"); // Start the cooperator
        StartCoroutine ( "getInfo");

    }}
    
    // Update is called once per frame
    Void Update ()
    {
        If (Input.GetKey (KeyCode.Escape) || Input.GetKey (KeyCode.Home))
        {
            Application.Quit ();
        }}
    }}
    Void OnGUI ()
    {
        If (GUI.Button (new Rect (Screen.width / 2-40,30,100,60), "screenshot"))
        {
            StartCoroutine ( "GetCapture");
        }}
    }}

    IEnumerator GetCapture ()
    {
        Yield return new WaitForEndOfFrame ();
        Int width = Screen.width;
        Int height = Screen.height;
        Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);
        Tex.ReadPixels (new Rect (0, 0, width, height), 0, 0, true);
        Byte [] imagebytes = tex.EncodeToPNG (); // Convert to png graph
        Tex.Compress (false); // Compress the screen cache
        //image.mainTexture = tex; // display the screen cache (thumbnails)
        String PicPath = "storage";
        File.WriteAllBytes (Application.persistentDataPath + "/" + Time.time + ".png", imagebytes); // store png graph
        Path.text = Application.persistentDataPath + "/";
    }}

    /// < summary>
    /// Sends a message to the server
    /// < / summary>
    /// < returns> The data. < / Returns>
    Public IEnumerator sendData ()
    {
        Int i = 0;
        While (true)
        {
            String sendStr = i.ToString () + "Hello server, I am Android";
            Byte [] sendBytes = UTF8Encoding.UTF8.GetBytes (sendStr);
            ClientSocket.Send (sendBytes);
            I ++;
            Yield return new WaitForSeconds (1f);
        }}
    }}
    /// < summary>
    /// Get the server response
    /// < / summary>
    /// < returns> The info. < / Returns>
    Public IEnumerator getInfo ()
    {
        While (true)
        {
            Byte [] revBytes = new byte [1024];
            Int bytes = clientSocket.Receive (revBytes, revBytes.Length, 0);
            String revStr = "";
            // revStr + = Encoding.ASCII.GetString (revBytes, 0, bytes);
            RevStr + = UTF8Encoding.UTF8.GetString (revBytes, 0, bytes);
            Debug.Log ( "Received Server Message:" + revStr);
            Text.text = "From Server:" + revStr;
            Yield return null;
        }}
}}
}}

LAN test no problem, whether it is to do the application or online games, and ultimately, Socket network data transmission is more necessary to understand the point of network knowledge, especially the TCP protocol, if wrong, please correct me.
     
         
         
         
  More:      
 
- Hadoop namenode do NFS disaster recovery (Server)
- Ubuntu 15.04 install Complete Guide (Linux)
- HttpClient Tutorial (Programming)
- Java-- get the reflection object information (Programming)
- Repair fatal error in Linux: lame / lame.h: No such file or dir Error (Linux)
- Taught you how to install Ubuntu Linux (Linux)
- Mumble installation source VoIP application on Ubuntu (Linux)
- Firewall - Internet Militarization (Linux)
- Linux boot process (Linux)
- CentOS 7 RHEL 7 to reset the root password (Linux)
- Retro terminal in Linux (Linux)
- Linux System Getting Started Tutorial: How to update outdated version of Ubuntu (Linux)
- Logging information through the web GUI (LogAnalyzer) (Server)
- An example of troubleshooting of embedded Linux OpenWRT (Linux)
- Standardized UNIX command-line tool (Linux)
- How to configure Ceph stored on CentOS 7.0 (Server)
- Linux (RHEL5) general optimization system security (Linux)
- Sshuttle A VPN-based transparent proxy that uses ssh (Server)
- How to install and use the malware detection tool LMD and ClamAV antivirus engine on Linux (Linux)
- Kafka + Log4j log implement centralized management (Server)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.