代码展示:客户端 public class Client { /** * @param args * @throws IOException * @throws UnknownHostException 未知主机异常 */ public static void main(String[] args) throws UnknownHostException, IOException { System.out.println("客户端开启……"); Socket socket=new Socket("192.168.1.100",10002); OutputStream out=socket.getOutputStream(); out.write("TCP演示案例".getBytes());
//读取服务端返回的数据,使用socket读取流 InputStream in=socket.getInputStream(); byte[] b=new byte[1024]; int len=in.read(b); System.out.println(new String(b,0,len)); socket.close(); } } 代码展示:服务端 public class Server { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.out.println("服务端开启……"); ServerSocket ss=new ServerSocket(10002); Socket s=ss.accept(); String ip=s.getInetAddress().getHostAddress(); InputStream in=s.getInputStream(); //创建缓冲区读取数据 byte[] bytes=new byte[1024]; int len=in.read(bytes); String text=new String(bytes,0,len); //打印客户端的IP地址和接收的数据 System.out.println(ip+":"+text);
//使用客户端socket对象的输出流给客户端返回数据 OutputStream out=s.getOutputStream(); out.write("服务端收到".getBytes());
//关闭资源 s.close(); ss.close();//服务端通常不关闭 } }
可以作为参考,注释已经写的很详细,亲
|