在wifi局域網下,手機可以和電腦通過socket通信。手機做服務端,電腦做客戶端;也可以反過來,電腦做服務端,手機做客戶端。
下面介紹的是手機作為服務端,電腦使用MFC編程作為客戶端,原理是,手機建立一個ServerSocket,並獲取自己的ip地址和端口port;然後電腦通過socket連接手機的ip:port。
核心代碼如下:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2012年資料/2月/8日/Android在wifi下手機與電腦的socket通信/
手機建立socketServer代碼
[html]
- private ServerSocket serverSocket = null;
- private Runnable mcreateRunnable = new Runnable()
- {
- public void run()
- {
- try {
- serverSocket = new ServerSocket(0);//系統分配端口
- getLocalIpAddress();//獲得手機的ip地址
- //方法用於等待客服連接
- mSocketServer = serverSocket.accept();
- //接受客服端數據BufferedReader對象
- mBufferedReaderServer = new BufferedReader(new InputStreamReader(mSocketServer.getInputStream()));
- //給客服端發送數據
- mPrintWriterServer = new PrintWriter(mSocketServer.getOutputStream(),true);
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
手機上獲取的ip地址代碼
[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 = "請連接IP:"+inetAddress.getHostAddress()+":"
- + serverSocket.getLocalPort()+ "\n";
- }
- }
- }
- }
- }
- catch (SocketException ex) {
- ex.printStackTrace(); }
- }
電腦上使用的是MFC編程,socket代碼如下
[html]
- DWORD clientThreadID;
- SOCKET clientSock;
- char server_address[50] = {0};
- char recv_message_client[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, "IP端口不對, 參考例子:192.168.12.134:8981", "提示", MB_OK);
- return FALSE;
- }
- memset(strPort, 0, sizeof(strPort));
- }
- else
- {
- MessageBox(0, "IP地址不對, 參考例子:192.168.12.134:8981", "提示", 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("系統拒絕連接,可能是輸入IP地址或端口不對:\n%s:%d", server_address, server_ip.sin_port);
- SetDlgItemText( FindWindow(NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, temp);
- MessageBox(0, "系統拒絕連接,可能是輸入IP地址或端口不對 ", "提示", MB_OK);
- return FALSE;
- }
- return TRUE;
- }
-
- DWORD WINAPI clientThreadFunc(LPVOID threadNum)
- {
- int length;
- CString temp;
-
- if(!InItClientSock())
- return 0;
- if(!ConnectSock())
- return 0;
-
- //等待連接的時候,連接可能被取消。
- if(clientThreadRun)
- SetDlgItemText(FindWindow(NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "已經連接上!");
- else
- {
- SetDlgItemText(FindWindow(NULL, WINDOWNHANDLERNAME), IDC_STATIC_IP, "請啟動服務!");
- 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, "接收到的信息", MB_OK);
- temp.Format("接收到的信息:\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("接收到的信息:\n%s",recv_message_client);
- }
-
- return 0;
- }