TestServer.java
package com.sxt.tcp; /* * 服务端 */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import javax.xml.crypto.Data; public class TestServer { public static void main(String[] args) throws IOException { System.out.println("服务端准备就绪!"); ServerSocket server = new ServerSocket(8888); //获取客户端的Socket! Socket accept = server.accept(); //读 Socket获取输入流 InputStream inputStream = accept.getInputStream(); DataInputStream dis = new DataInputStream(inputStream); //读出数据 String string = dis.readUTF(); System.out.println(string); //实现双向通信 写 输出流 数据流 DataOutputStream dos = new DataOutputStream(accept.getOutputStream());//注意! dos.writeUTF("服务端说:我已经收到!"); accept.close(); server.close(); } }
TestClient.java
package com.sxt.tcp2; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /* 基于TCP协议的Socket编程 * 双向通信 * 通过IO流传输数据 * */ //客户端 public class TestClient { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket = new Socket(InetAddress.getLocalHost(), 8888); OutputStream os = socket.getOutputStream();//socket获取输出流 //数据写到客户端 输出流 数据流(4个特殊的方法) DataOutputStream dos = new DataOutputStream(os); //数据写到服务端 dos.writeUTF("客户端说:你好服务器!"); //接收服务端的反馈信息 读 输入流 DataInputStream dis = new DataInputStream(socket.getInputStream());//注意! String string = dis.readUTF(); System.out.println(string); socket.close(); } }