最近,要做一个东西,是android客户端要与VC写的服务器端进行数据连接与交换,无奈,先从java测试吧,android还没弄,其实只要是遵循的同一个协议就可以通信了,不管你的客户端和服务器是什么编程语言,什么操作系统,都不重要,重要的是遵循TCP或UDP协议等,先不废话了,上代码再说,
服务器端VC代码如下:
void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return; } if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 ) { WSACleanup( ); return; } //一下代码获得IP和计算机名 char name[255]; char* ip = NULL; PHOSTENT hostInfo; if (gethostname(name,sizeof(name)) == 0) { if (hostInfo = gethostbyname(name)) { ip = inet_ntoa(*(in_addr*)*(hostInfo->h_addr_list)); } } printf("%s--%s\n",ip,name); //获取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(6000); //监听端口 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[266] = {0}; recv(sockConn,recvBuf,266,0); std::cout << recvBuf << std::endl; } //关闭套接字 closesocket(sockSrv); WSACleanup(); }
当然还要加入WS2_32.LIB文件。
客户端代码如下:
import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; public class ClientSocket extends Socket{ Socket socket; /** * 构造 */ public ClientSocket(String ip , int port){ try { socket = new Socket(ip, port); System.out.println("连接建立成功: site:"+ ip +" port:"+port); } catch (UnknownHostException e) { System.out.println("失败"); e.printStackTrace(); } catch (IOException e) { System.out.println("失败"); 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) throws SocketException { ClientSocket socket = new ClientSocket("127.0.0.1", 6000); socket.send("zhouxuguang"); socket.close(); System.out.println(socket.getReceiveBufferSize()); System.out.println(socket.getSendBufferSize()); } }
测试结果如下:
客户端:
连接建立成功: site:127.0.0.1 port:6000
发送的内容:zhouxuguang
8192
8192
服务器端:
当然,这只是简单的字符串数据传输,复杂的消息结构体的传输还有待进一步研究。下一步要研究android上怎么与VC通信。