Socket通信 客户端和服务器端的通信 客户端

客户端代码:
public void getSocket(){
		//获取到当前网络的ip地址
		InetAddress ia;
		//创建客户端对象并实例化
		Socket s ;
		try {
			ia = InetAddress.getLocalHost();
			 s = new Socket(ia.getHostAddress(),8889);
			 //创建输出流对象并实例化
			 OutputStream out = s.getOutputStream();
			 //创建转换流的对象
//			 OutputStreamWriter ow = new OutputStreamWriter(out);
			 PrintWriter pw = new PrintWriter(out);
			 //创建缓存流获取到控制台输入的数据
			 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			 //创建输入流
			 InputStream in = s.getInputStream();
			 //获取到服务器传递过来的信息
			 BufferedReader br1 = new BufferedReader(new InputStreamReader(in));
			 boolean flag = true;
			 while(flag){
				 String str = br.readLine();
				 //判断是否结束通话
				 if("886".equals(str)){
					 flag = false;
//					 System.out.println(flag);
				 }
				 pw.write(str+"\r\n");
				 pw.flush();//提交
				 String str1 = br1.readLine();
				 if("886".equals(str1)){
					 flag = false;
				 }
				 //不结束
				 System.out.println("服务器发回来的信息:"+str1);
				 System.out.println(flag);
				 
				 
			 }
			 System.out.println("走出循环");
			 br.close();
			 pw.close();
//			 br1.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

你可能感兴趣的:(android,java)