//socket编程 public class TcpTest { //客户端 public void client(){ Socket socket=null; OutputStream os=null; InputStream is=null; try { socket = new Socket(InetAddress.getByName("127.0.0.1"), 8000); //发出输出流 给服务端发信息 os = socket.getOutputStream(); os.write("我是客户端".getBytes()); //得到服务端发来的信息 is=socket.getInputStream(); byte[] b=new byte[20]; int len; while ((len=is.read(b))!=-1){ String str =new String(b,0,len); System.out.print(str); } }catch (IOException e){ e.printStackTrace(); }finally { //这里最好加if判定 try{ is.close(); os.close(); socket.close(); }catch (IOException e){ e.printStackTrace(); } } } //服务端 public void server(){ ServerSocket ss=null; Socket s=null; InputStream is=null; OutputStream os=null; try{ ss=new ServerSocket(8000); s=ss.accept(); //获取输入流 获取客户端的信息 is=s.getInputStream(); byte[] b=new byte[20]; int len; while ((len=is.read(b))!=-1){ String str =new String(b,0,len); System.out.print(str); } //收到客户端的ip System.out.print(s.getInetAddress().getHostAddress()); //给客户端发信息 os=s.getOutputStream(); os.write("get".getBytes()); }catch (IOException e){ e.printStackTrace(); }finally { try{ os.close(); is.close(); s.close(); ss.close(); }catch (IOException e){ e.printStackTrace(); } } } }
08-09
08-09
08-09
08-09