java_tcp_简单示例
package netProgram; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { System.out.println("-------TCPServer--------"); ServerSocket server = new ServerSocket(8888); // 阻塞式的等待连接 Socket client = server.accept(); DataOutputStream writer = new DataOutputStream(client.getOutputStream()); writer.writeUTF("成功建立连接"); writer.flush(); writer.close(); client.close(); server.close(); // server.close(); } }
package netProgram; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws IOException { System.out.println("-------TCPClient--------"); //建立连接 Socket client = new Socket("localhost", 8888); DataInputStream reader = new DataInputStream(client.getInputStream()); String s = reader.readUTF(); System.out.println(s); reader.close(); client.close(); } }