客户端代码:
public class ClientDemo { public static void main(String[] args) throws IOException { //创建客户端的Socket对象 Socket s = new Socket("192.168.50.76",12345); //获取输出流,写数据 OutputStream os = s.getOutputStream(); os.write("hello TCP 我来了".getBytes()); //释放资源 s.close(); } }
服务器端代码:
public class ServerDemo { public static void main(String[] args) throws IOException { //创建服务器端的Socket对象 ServerSocket ss= new ServerSocket(12345); //监听客户端连接,返回一个Socket对象 Socket s = ss.accept(); //获取输入流,读数据,并把数据显示在控制台 InputStream is = s.getInputStream(); byte[] bys = new byte[1024]; int len = is.read(bys); String data = new String(bys,0,len); System.out.println("数据是:"+data); //释放资源 s.close(); ss.close(); } }
服务端接受到数据的结果:
原文:https://www.cnblogs.com/pxy-1999/p/12845623.html