C++Builder XE2 写一个客户端与java通讯

5 篇文章 0 订阅

C++Builder 中主要用到的控件是TIdTcpClient

C++代码

        
         
         ConnData cd= form_config->getConnData();

         idtcpclnt1->Host=cd.host;
 	 idtcpclnt1->Port=cd.port;
	 idtcpclnt1->Connect();
	 try{
		 if(idtcpclnt1->Connected())
		 {
		   idtcpclnt1->Socket->WriteBufferOpen();
			int head=998;
			 TBytes byte;
			 byte.set_length(4);
			 byte[0]=head;
			 byte[1]=head>>8;
			 byte[2]=head>>16;
			 byte[3]=head>>24;
		   idtcpclnt1->Socket->Write(byte,4);
		   int len=cd.userName.Length();
			 byte[0]=len;
			 byte[1]=len>>8;
			 byte[2]=len>>16;
			 byte[3]=len>>24;
		   idtcpclnt1->Socket->Write(byte,4);

		   TBytes MsgStr;
		   MsgStr=cd.userName.BytesOf();
		   idtcpclnt1->Socket->Write(MsgStr,len);
		   idtcpclnt1->Socket->WriteBufferFlush();
		   int recv=idtcpclnt1->Socket->ReadLongInt();
		   if(recv!=345)
		   {
			   idtcpclnt1->Disconnect();
			   return;
           }
		   int filesize=idtcpclnt1->Socket->ReadLongInt();
		   TFileStream *fs=new TFileStream("temp/123456789.xml",fmCreate);
		   idtcpclnt1->Socket->ReadStream(fs,filesize);
		   //delete fs;
		   //Application->MessageBox(IntToStr(filesize).w_str(),L"提示信息框",MB_ICONASTERISK);
		   idtcpclnt1->Disconnect();
		   try{
			 this->parseXML(fs);
		   }catch(Exception &e){
			  Application->MessageBoxW(e.Message.w_str(),L"处理数据异常",MB_ICONWARNING);
		   }
		   fs->Free();

		 }else{
			Application->MessageBox(L"连接失败!",L"提示信息框",MB_ICONWARNING);
		 }
	 }catch(...)
	 {
		Application->MessageBox(L"连连异常!",L"提示信息框",MB_ICONWARNING);
		if(idtcpclnt1->Connected())
           idtcpclnt1->Disconnect();
	 }

java代码:

              ServerSocket ss;
		try{
		   
		   ss=new ServerSocket(1234);
		   while(true)
		   {
			  Socket s=ss.accept();
			  DataInputStream in=new DataInputStream(new BufferedInputStream(s.getInputStream()));
			  DataOutputStream out=new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
			  int head=ByteUtils.readInt(in);
			  System.out.println("head:"+head);
			  int len=ByteUtils.readInt(in);
			  System.out.println("len:"+len);
			  byte[] bytes=new byte[len];
			  in.read(bytes);
			  System.out.println("内容:"+new String(bytes));
			  out.writeInt(345);
			  File file=new File("C:\\123456789.xml");
			  int size=(int)file.length();
			  out.writeInt(size);
			  FileInputStream fin=new FileInputStream(file);
			  IOUtils.copy(fin,out);
			  IOUtils.closeQuietly(fin);
			  out.flush();
			  //Thread.sleep(10000);
			  in.close();
			  out.close();
			  s.close();
			  
			  
			  
		   }
		   
		}catch(Exception e){
			e.printStackTrace();
		}
	}

测试成功!希望能对大家有帮助

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值