//客户端
io.open();//打开控制台

import win;
import wsock;
import wsock.err;

// 初始化 Winsock.	
if(! wsock.open() ){
	io.print("打开wsock错误", wsock.err.lasterr() );
	return;
}
 

//建立 socket 
var hSocket= wsock.socket(0x2/*_AF_INET*/,0x1/*_SOCK_STREAM 建立流式套接口*/,0x6/*_IPPROTO_TCP*/ )
if( hSocket= _INVALID_SOCKET ){
	io.print("客户端创建套接字错误");
	wsock.close() //关闭wsock
	return;
}

 
var service = wsock.sockaddr_in();
service.sin_family = 0x2/*_AF_INET*/
service.sin_addr.S_un.S_addr = wsock.inet_addr( "127.0.0.1" )
service.sin_port = wsock.htons(7510)

//之后服务端就调用accept( )来接收连接.客户端在建立套接口后就可调用connect()和服务器建立连接
if wsock.connect( hSocket,service,raw.sizeof(service)) =-1/*_SOCKET_ERROR*/	{
	io.print("连接服务端失败");
	wsock.closesocket(hSocket)
	wsock.close() //关闭wsock
	return;
}
 
 
 
io.print("连接端口成功，正在接收文件!")
 

var filelen;
var reads_count = 0;
file = io.open("/test.rar","w+b");//注意io.open默认是文本方式写入的,b指定二进制模式
do{
	sleep(1)
	var reads,recvbuf = wsock.recv(	hSocket,1024,1024,0) 
	if ( reads=-1 ){
		 io.print( "客户端接收错误");
		 io.print( wsock.err.lasterr() );
		 break;
	}
	else if( reads>0 ) { 
		 pos =	string.find( recvbuf,"<end_sock>") ;
		 if( pos ){
		 	recvbuf = string.left(recvbuf,pos);
		 	io.print("共接收" + (reads_count + pos))
		 	file.write( recvbuf ); 
		 	break;
		 };
		 io.print("接收" + reads)
		 reads_count += reads;

		 if(reads<1024){
		 	recvbuf=string.left(recvbuf,reads)
		 	file.write( recvbuf );	
		 		break; //缓冲区没读满，也是读完了
		 	}
		 else{
		 	file.write( recvbuf );
		 	}
		 	
	} 
		
}while(reads!=-1 ) 

file.close();

io.print("客户端接收文件完成");

////待数据传送结束后,双方调用close()关闭套接口
wsock.closesocket(hSocket)
wsock.close();
