socket通信 简单的客户端和服务器的通信 服务器的代码

2/22/2017来源:ASP.NET技巧人气:2252

public void testServer(){
		try {
			ServerSocket ss = new ServerSocket(8889);
			//接收客户端发过来的信息
			Socket s = ss.accept();
			//通过缓存流来读取信息
			InputStream in = s.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			//给客户端发送信息,需要从控制台输入信息
			BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
			//创建输出流给客户端发送
			OutputStream out = s.getOutputStream();
			//创建写的对象
//			OutputStreamWriter ow = new OutputStreamWriter(out);
			PRintWriter pw = new PrintWriter(out);
			boolean flag = true;
			while(flag){
				String str = br.readLine();
				//判断是否结束通话
				if( "886".equals(str)){
					flag = false;
				}
				//不结束
				System.out.println("客户端发来的信息:"+str);
				String str1 = br1.readLine();
				if("886".equals(str1)){
					flag = false;
				}
				pw.write(br1.readLine()+"\r\n");
				pw.flush();//提交
					System.out.println(flag);
				
			}
			System.out.println("走出循环");
			br.close();
//			pw.close();
//			br1.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}以上为服务器端代码: