C++ 作為Client端
view plaincopy to clipboardprint?
復制代碼 代碼如下:
// Client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#pragma comment(lib,"ws2_32.lib")
#define MAX_BUF_SIZE 1024
#define PORT_NUMBER 12581
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wSaData;
WORD dwSockVersion = MAKEWORD(2,2);
if (0 != WSAStartup(dwSockVersion,&wSaData)) //協商版本號
{
printf("Arrange Version Failure");
return -1;
}
SOCKET nSocket;
nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //創建TCP socket
if (INVALID_SOCKET == nSocket)
{
printf("invalid socket");
WSACleanup();
return -1;
}
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
sa.sin_port = htons(PORT_NUMBER);
if ( 0 != connect( nSocket,( const SOCKADDR * )&sa, sizeof(sa) ) )
return -1;
char buf[MAX_BUF_SIZE] = {0};
char tmp[MAX_BUF_SIZE] = {0};
strcpy(tmp,"this is Client!");
int nSend = send(nSocket, tmp, (int)strlen(tmp), 0);
int nRecv = 0;
nRecv = recv(nSocket, buf, MAX_BUF_SIZE, 0);
if (nRecv > 0)
{
printf("%s\n",buf);
}
closesocket(nSocket);
WSACleanup();
return 0;
}
Android 模擬器,JAVA作為Serve端
view plaincopy to clipboardprint?
復制代碼 代碼如下:
package com.Android.SocketTest;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
public class SocketTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StartAcceptSocket();
}
private void StartAcceptSocket()
{
try
{
short nPort = 31012;
ServerSocket m_pServerSocket = new ServerSocket(nPort); //初始化socket
Socket pAccSocket = m_pServerSocket.accept(); //accept 阻塞等待
new RunningThread(pAccSocket).start(); //新建一個線程進行數據收發
}catch(Exception e)
{
e.printStackTrace();
}
}
public class RunningThread extends Thread
{
private Socket msocket = null;
RunningThread(Socket s)
{
this.msocket = s;
}
public void run()
{
byte [] pRecbyte = new byte[1024];
String sSend = "hello Client! this is Server";
byte [] pSendByte = new byte[1024];
pSendByte = sSend.getBytes();
while(true)
{
try
{
DataInputStream sRead = new DataInputStream(msocket.getInputStream()); //讀取
int nRec = sRead.read(pRecbyte);
if(nRec > 0 )
{
//System.out.println("receive client message success!");
DataOutputStream sWrite = new DataOutputStream(msocket.getOutputStream());
sWrite.write(pSendByte); //發送
break;
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
android 模擬器使用的IP 地址為"127.0.0.1";使用PC機的端口號,在模擬器TCP連接調試之前必須使用android sdk 使用的工具進行一次端口映射。如圖所示。即使用 Sdk 中的Tools下abd 工具,在cmd 窗口中運行E:\\install\\android\\Android\\android-sdk-windwows\\tools\\adb forward tcp:12581 tcp:31012" 前面目錄為android sdk Tools 所在目錄。根據本機情況而定。