客户端:
public class Client { public static void main(String[] args) throws Exception{ //创建客户端连接 Socket socket = new Socket("10.41.12.83",8999); //获取输出流 OutputStream outputStream = socket.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); //输出数据 dataOutputStream.writeUTF("你好,我是客户端小白"); //释放资源 dataOutputStream.close(); outputStream.close(); } }
服务端:
public class Server { public static void main(String[] args) throws Exception{ //创建服务端 ServerSocket serverSocket = new ServerSocket(8999); //接收客户请求 Socket accept = serverSocket.accept(); //输入流读取数据 InputStream inputStream = accept.getInputStream(); DataInputStream dataInputStream = new DataInputStream(inputStream); //接收数据并传输 String s = dataInputStream.readUTF(); System.out.println("我是服务端,我接收到了:"+s); //释放资源 dataInputStream.close(); inputStream.close(); } }