输入输出操作
可以这样理解:
BufferedReader/BufferedWriter使用三部曲:
服务器操作
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class Server {private static int port = 8002;//设置端口号public static void main(String[] args)throws IOException {ServerSocket serverSocket = new ServerSocket(port);//第一步设置服务器端口号System.out.println("等待连接....");Socket socket = serverSocket.accept();//第二步等待客户端发送连接请求System.out.println("客户端已连接成功");//第三步创建和客户端的的输入输出对象BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));bufferedWriter.write("写入要传输给客户端的内容");bufferedWriter.flush();//注意刷新后客户端才能收到//关闭bufferedReader.close();bufferedWriter.close();socket.close();}
}
客户端操作
import java.io.*;
import java.net.Socket;
public class Client {static Socket socket;static String serverHost = "10.200.142.214";//服务器端的ip地址static int serverPort = 8002;//服务器端的端口号public static void main(String[] args)throws IOException {socket = new Socket(serverHost,serverPort);//请求连接,连接的目的服务器的ip和端口号要作为参数BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));String r = bufferedReader.readLine();//读取一行服务器端写入的文本,注意文本要以换行符或者回车结尾//关闭bufferedReader.close();bufferedWriter.close();socket.close();}
}