package com.fgy.demo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * 服务器端 */ public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8888); Socket socket = server.accept(); InputStream is = socket.getInputStream(); byte[] b = new byte[1024]; int len = is.read(b); System.out.println(new String(b, 0, len)); OutputStream os = socket.getOutputStream(); os.write("收到,谢谢!".getBytes()); socket.close(); server.close(); } }
package com.fgy.demo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * 客户端 */ public class TCPClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1", 8888); OutputStream os = socket.getOutputStream(); os.write("你好,服务器!".getBytes()); InputStream is = socket.getInputStream(); byte[] b = new byte[1024]; int len = is.read(b); System.out.println(new String(b, 0, len)); socket.close(); } }