Bootstrap

vc++ 与 android/java 进行socket通信

开发环境

客户端:java Eclipse8.5 

服务端:vs2010 标准win32应用程序(未使用.netframewok类库,或 mfc)

 

需要注意的是,在使用vc++ socket编程前 ,需要给c++项目添加WS2_32.lib动态库的链接。需要手动在vs2010内设置。

 

服务端代码:

#include "stdafx.h"
#include "Listener.h"

/*
  启动监听器。
*/
void Listener::startListener(void)
{
	wVersionRequested = MAKEWORD( 1, 1 );
	
	err = WSAStartup( wVersionRequested, &wsaData );

	//0为成功,其他为具体错误信息
	if ( err != 0 ) {
	 return;
	}

	if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 ) {
		WSACleanup( );
		return;
    }

	//获取socketServer对象
	SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //设置监听地址
	addrSrv.sin_family           = AF_INET;           //监听类型
	addrSrv.sin_port             = htons(9758);       //监听端口
	
	bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
	listen(sockSrv,10);

	SOCKADDR_IN addrClient;
	int len=sizeof(SOCKADDR);
	
	while(true)
	{
		//开始接受数据,等待
		SOCKET sockConn = accept(sockSrv,(SOCKADDR*)&addrClient,&len);
		char recvBuf[4] = {0};
		recv(sockConn,recvBuf,4,0);
		std::cout << recvBuf[0] << std::endl;
		closesocket(sockConn);
    }
}


 

客户端:

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;


public class ClientScoket{
	
	Socket socket;
	
	/**
	 * 构造
	 */
	public ClientScoket(String ip , int port){
		
		try {
			socket = new Socket(ip, port);
			System.out.println("连接建立成功: site:"+ ip +" port:"+port);
		} catch (UnknownHostException e) {
			System.out.println("失败1");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("失败2");
			e.printStackTrace();
		}
	}
	
	public String send(String msg)
	{
		try {
			System.out.println("发送的内容:" + msg);
			
			PrintWriter out = new PrintWriter(socket.getOutputStream());	

			out.print(msg);
			out.flush();
			
			return null;
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void close()
	{
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ClientScoket socket = new ClientScoket("192.168.0.101", 9758);
		socket.send("haha");
		socket.close();
	}


}


 

本程序赞未考虑乱码问题,特使用英文字符传递。

;