C # data interaction between mobile terminals and PCs

Source: Internet
Author: User

C # data interaction between mobile terminals and PCs

Note: For smartphones with more and more powerful features, applications supporting mobile phone user data synchronization, backup, recovery, and other protection measures are in urgent need. In addition to data protection, users prefer to integrate their mobile phones and PCs, as well as remote servers. Users hope that operations on the mobile phone end can be transferred to the PC end. For PC-side large screen computers, the same operation can save a lot of time. For powerful mobile phones, nearly 1/2 of applications can be synchronized on PCs. Therefore, the planning of PC-side applications should be taken as a system. At the same time, ensure that the mainstream interaction modes on mobile phones and PCS should be consistent. Personal Opinion: data integration and management diversification are a trend of future development. Next, let's take a look at today's learning. Today's lab Mobile End and PC end Data Interaction and analysis.

1. How to achieve data interaction between mobile terminals and PCs?

Answer: 1. Bluetooth 2, NFC Technology 3, infrared 4, Socket.

Similarities and differences between NFC and Bluetooth:

Similarities: close-range transmission.

Difference: NFC is better than infrared and Bluetooth transmission. As a consumer-oriented transaction mechanism, NFC is faster, more reliable, and much simpler than infrared, and data can be transmitted without strict alignment like infrared. Compared with Bluetooth, NFC is applicable to close-range transactions, and is suitable for exchanging important data such as financial information or sensitive personal information. Bluetooth can make up for the shortcomings of NFC communication distance and is suitable for long-distance data communication. Therefore, NFC and Bluetooth complement each other and coexist. In fact, the fast and light NFC protocol can be used to guide the Bluetooth pairing process between two devices, promoting the use of Bluetooth. However, to achieve long-distance data transmission, you can only use Socket,

The following code is analyzed:

First, create Server. cs on the PC

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 Address
String host = "192.168.1.100 ";

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

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

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

// Establish an association between the socket and the local endpoint
Socket. Bind (ipe );
While (true)
{
// Start listening on the port
Socket. Listen (0 );

Console. WriteLine ("the service is enabled. Please wait..." + DateTime. Now. ToString () + DateTime. Now. Millisecond. ToString ());

// Create a new Socket for the new connection. The purpose is to establish a connection for the client.
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 for receiving client data
Byte [] recbyte = new byte [1, 1024];

ReceiveData ();

SendDataToClient = new Thread (sendData );
SendDataToClient. Start ();

}
}

Public static void sendData ()
{

While (true)
{
Console. WriteLine ("send to client \ n ");
// The service end sends a message back to the client
String strSend = "Hello Android Client! "+ DateTime. Now. Second;
// String strSend = "success ";
Byte [] sendByte = new byte [1, 1024];
// Convert the sent string to byte []
SendByte = UTF8Encoding. UTF8.GetBytes (strSend );
// The server sends 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>
/// Receive messages
/// </Summary>
Public static void ReceiveData ()
{
If (serverSocket. ReceiveBufferSize> 0)
{
ServerSocket. BeginReceive (MsgBuffer, 0, MsgBuffer. Length, 0, new AsyncCallback (effececallback), null );
}
}

Private static void extends ecallback (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;
// Data can be processed on demand this time

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

Console. WriteLine ("received server 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
}
}

The script written in Unity3D on the Mobile End is mounted on 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 Address
String LocalIP = "192.168.1.100 ";
// 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 collaboration program
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 ),""))
{
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
Tex. Compress (false); // compresses the screen cache.
// Image. mainTexture = tex; // display the screen cache (thumbnail)
String PicPath = "storage ";
File. WriteAllBytes (Application. persistentDataPath + "/" + Time. time + ". png", imagebytes); // store png Images
Path. text = Application. persistentDataPath + "/";
}

/// <Summary>
/// Send 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 [1, 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;
}
}
}

Server running result:

Server return message code: string strSend = "Hello Android Client! "+ DateTime. Now. Second;

There is no problem in testing on the LAN. In the future, whether it is for applications or online games, Socket network data transmission is indispensable. It is necessary to know more about the network, especially the TCP protocol, if any error occurs, please correct it.

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.