Android uses a socket to communicate with a computer over wifi.

Source: Internet
Author: User

In a Wi-Fi LAN, a mobile phone can communicate with a computer through a socket. The mobile phone acts as the server and the computer acts as the client. Alternatively, the computer acts as the server and the mobile phone acts as the client.

The following describes how to use a mobile phone as the server and a computer using MFC programming as the client. The principle is that the mobile phone establishes a ServerSocket and obtains its own IP address and port; then the computer connects to the ip Address: port of the mobile phone through socket.




 

Code: http://download.csdn.net/detail/menghnhhuan/4050488

 

Code for creating socketServer on the mobile phone

[Html] private ServerSocket serverSocket = null;
Private Runnable mcreateRunnable = new Runnable ()
{
Public void run ()
{
Try {
ServerSocket = new ServerSocket (0); // The system allocates a port.
GetLocalIpAddress (); // get the IP address of the mobile phone
// Method used to wait for customer service connection
MSocketServer = serverSocket. accept ();
// Accept the BufferedReader object
MBufferedReaderServer = new BufferedReader (new InputStreamReader (mSocketServer. getInputStream ()));
// Send data to the Customer Service
MPrintWriterServer = new PrintWriter (mSocketServer. getOutputStream (), true );

} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
};
Private ServerSocket serverSocket = null;
Private Runnable mcreateRunnable = new Runnable ()
{
Public void run ()
{
Try {
ServerSocket = new ServerSocket (0); // The system allocates a port.
GetLocalIpAddress (); // get the IP address of the mobile phone
// Method used to wait for customer service connection
MSocketServer = serverSocket. accept ();
// Accept the BufferedReader object
MBufferedReaderServer = new BufferedReader (new InputStreamReader (mSocketServer. getInputStream ()));
// Send data to the Customer Service
MPrintWriterServer = new PrintWriter (mSocketServer. getOutputStream (), true );

} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
};
 

IP address code obtained on the mobile phone

[Html] public String getLocalIpAddress ()
{
Try {
For (Enumeration <NetworkInterface> en = NetworkInterface. getNetworkInterfaces (); en. hasMoreElements ();)
{
NetworkInterface intf = en. nextElement ();
For (Enumeration <InetAddress> enumIpAddr = intf. getInetAddresses (); enumIpAddr. hasMoreElements ();)
{
InetAddress inetAddress = enumIpAddr. nextElement ();
// If (! InetAddress. isLoopbackAddress ())
{
// If (inetAddress. isSiteLocalAddress ())
{
String ip = "Please connect IP:" + inetAddress. getHostAddress () + ":"
+ ServerSocket. getLocalPort () + "\ n ";
}
}
}
}
}
Catch (SocketException ex ){
Ex. printStackTrace ();}
}
Public String getLocalIpAddress ()
{
Try {
For (Enumeration <NetworkInterface> en = NetworkInterface. getNetworkInterfaces (); en. hasMoreElements ();)
{
NetworkInterface intf = en. nextElement ();
For (Enumeration <InetAddress> enumIpAddr = intf. getInetAddresses (); enumIpAddr. hasMoreElements ();)
{
InetAddress inetAddress = enumIpAddr. nextElement ();
// If (! InetAddress. isLoopbackAddress ())
{
// If (inetAddress. isSiteLocalAddress ())
{
String ip = "Please connect IP:" + inetAddress. getHostAddress () + ":"
+ ServerSocket. getLocalPort () + "\ n ";
}
}
}
}
}
Catch (SocketException ex ){
Ex. printStackTrace ();}
}
 

The computer uses MFC programming. The socket code is as follows:


[Html] DWORD clientThreadID;
SOCKET clientSock;
Char server_address [50] = {0 };
Char recv_message_client [1, 256] = {0 };
Struct sockaddr_in server_ip;
BOOL clientThreadRun = false;
// Client
BOOL InItClientSock ()
{
// Define Variable
WORD wVersionrequested;
WSADATA wsaData;
 
WVersionrequested = MAKEWORD (2, 0 );

// Start Sock
Int err = WSAStartup (wVersionrequested, & wsaData );
If (err =-1)
{
MessageBox (0, "WSAStartup err", "error", MB_ OK );
Return FALSE;
}
Return TRUE;
}
BOOL ConnectSock ()
{
SOCKET clientSockConnect;
U_short port;
 
// Ini Sock
ClientSock = socket (AF_INET, SOCK_STREAM, 0 );
If (ServerSock <0)
{
MessageBox (0, "scoker err ",
"Err", MB_ OK );
Return FALSE;
}
 
Char * strPort = strstr (server_address ,":");
 
If (strPort! = NULL) & (strlen (strPort)> 2 ))
{
Port = atoi (strPort + 1 );
If (port = 0)
{
MessageBox (0, "the IP port is incorrect. For example: 192.168.12.134: 8981", "prompt", MB_ OK );
Return FALSE;
}
Memset (strPort, 0, sizeof (strPort ));
}
Else
{
MessageBox (0, "Incorrect IP address, refer to example: 192.168.12.134: 8981", "prompt", MB_ OK );
Return FALSE;
}
 
// Connect
Server_ip.sin_family = AF_INET;
Server_ip.sin_port = (port & 0xff00)> 8) | (port & 0x00ff) <8 );
Server_ip.sin_addr.S_un.S_addr = inet_addr (server_address );
 
ClientSockConnect = connect (clientSock, (struct sockaddr *) & server_ip, sizeof (server_ip ));
If (clientSockConnect! = 0)
{
CString temp;
Temp. Format ("the system rejects the connection. The input IP address or port is incorrect: \ n % s: % d", server_address, server_ip.sin_port );
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, temp );
MessageBox (0, "the system rejects the connection. The input IP address or port is incorrect.", "prompt", MB_ OK );
Return FALSE;
}
Return TRUE;
}
 
Dword winapi clientThreadFunc (LPVOID threadNum)
{
Int length;
CString temp;
 
If (! InItClientSock ())
Return 0;
If (! ConnectSock ())
Return 0;

// The connection may be canceled when the connection is waiting.
If (clientThreadRun)
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "connected! ");
Else
{
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "please start the service! ");
Return 0;
}
 
// Send (NewSock, (char *) & FALG, sizeof (FALG) + 1, MSG_OOB );
While (clientThreadRun)
{
If (length = recv (clientSock, (char *) recv_message_client, sizeof (recv_message_client), 0)> 0)
{
// MessageBox (0, recv_message, "received information", MB_ OK );
Temp. Format ("received information: \ n % s", recv_message_client );
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, temp );
 
AnalyseCommand (recv_message_client );
Memset (recv_message_client, 0, sizeof (recv_message_client ));
}
Temp. Format ("received information: \ n % s", recv_message_client );
}
 
Return 0;
}
DWORD clientThreadID;
SOCKET clientSock;
Char server_address [50] = {0 };
Char recv_message_client [1, 256] = {0 };
Struct sockaddr_in server_ip;
BOOL clientThreadRun = false;
// Client
BOOL InItClientSock ()
{
// Define Variable
WORD wVersionrequested;
WSADATA wsaData;

WVersionrequested = MAKEWORD (2, 0 );
 
// Start Sock
Int err = WSAStartup (wVersionrequested, & wsaData );
If (err =-1)
{
MessageBox (0, "WSAStartup err", "error", MB_ OK );
Return FALSE;
}
Return TRUE;
}
BOOL ConnectSock ()
{
SOCKET clientSockConnect;
U_short port;

// Ini Sock
ClientSock = socket (AF_INET, SOCK_STREAM, 0 );
If (ServerSock <0)
{
MessageBox (0, "scoker err ",
"Err", MB_ OK );
Return FALSE;
}

Char * strPort = strstr (server_address ,":");

If (strPort! = NULL) & (strlen (strPort)> 2 ))
{
Port = atoi (strPort + 1 );
If (port = 0)
{
MessageBox (0, "the IP port is incorrect. For example: 192.168.12.134: 8981", "prompt", MB_ OK );
Return FALSE;
}
Memset (strPort, 0, sizeof (strPort ));
}
Else
{
MessageBox (0, "Incorrect IP address, refer to example: 192.168.12.134: 8981", "prompt", MB_ OK );
Return FALSE;
}

// Connect
Server_ip.sin_family = AF_INET;
Server_ip.sin_port = (port & 0xff00)> 8) | (port & 0x00ff) <8 );
Server_ip.sin_addr.S_un.S_addr = inet_addr (server_address );

ClientSockConnect = connect (clientSock, (struct sockaddr *) & server_ip, sizeof (server_ip ));
If (clientSockConnect! = 0)
{
CString temp;
Temp. Format ("the system rejects the connection. The input IP address or port is incorrect: \ n % s: % d", server_address, server_ip.sin_port );
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, temp );
MessageBox (0, "the system rejects the connection. The input IP address or port is incorrect.", "prompt", MB_ OK );
Return FALSE;
}
Return TRUE;
}

Dword winapi clientThreadFunc (LPVOID threadNum)
{
Int length;
CString temp;

If (! InItClientSock ())
Return 0;
If (! ConnectSock ())
Return 0;
 
// The connection may be canceled when the connection is waiting.
If (clientThreadRun)
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "connected! ");
Else
{
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "please start the service! ");
Return 0;
}

// Send (NewSock, (char *) & FALG, sizeof (FALG) + 1, MSG_OOB );
While (clientThreadRun)
{
If (length = recv (clientSock, (char *) recv_message_client, sizeof (recv_message_client), 0)> 0)
{
// MessageBox (0, recv_message, "received information", MB_ OK );
Temp. Format ("received information: \ n % s", recv_message_client );
SetDlgItemText (FindWindow (NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, temp );

AnalyseCommand (recv_message_client );
Memset (recv_message_client, 0, sizeof (recv_message_client ));
}
Temp. Format ("received information: \ n % s", recv_message_client );
}

Return 0;
}


From menghnhhuan's column


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.