客户端:
import java.io.*; import java.net.*; public class TcpClient2 { public static void main(String[] args) throws Exception{ // 创建客户端的socket服务,指定目的主机和端口。 Socket s=new Socket("192.168.2.100",10006); //获取socket流中的输出流 OutputStream out=s.getOutputStream(); out.write("你好,服务端".getBytes()); InputStream in=s.getInputStream(); byte[] buf=new byte[1024]; int len=in.read(buf); in.read(buf); System.out.println(new String(buf,0,len)); s.close(); } }
服务器端:import java.io.*; import java.net.*; public class Tcpserver2 { public static void main(String[] args) throws Exception{ // 建立服务端的socket服务,并监听一个端口 ServerSocket ss=new ServerSocket(10006); //通过accept方法获取连接过来的客户端对象 Socket s=ss.accept(); String ip=s.getInetAddress().getHostAddress(); System.out.println("ip:"+ip); //获取客户端发送过来的数据,使用客户端的读取流方法来读取数据 InputStream in=s.getInputStream(); byte[] buf=new byte[1024]; int len=in.read(buf); System.out.println(new String(buf,0,len)); OutputStream out=s.getOutputStream(); out.write("你好,收到你的信息".getBytes()); s.close(); } }