TCP字符流编程

客户端连接服务端流程

TCP字符流编程_第1张图片

package com.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听,要求:在本机的其他服务没有监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端,在9999端口监听,等待连接。。。");
        //2.当没有客户端连接9999端口,程序会阻塞,等待连接
        //如果有客户端连接,会返回一个socket对象
        //ServerSocket 可以通过accept() 返回多个socket[多个客户端连接服务端的并发]
        Socket socket = serverSocket.accept();
        System.out.println("服务端socket=" + socket.getClass());
        //3.获取socket关联的输入流 读取客户端写入到数据通道的数据
        InputStream inputStream = socket.getInputStream();
        //4.IO读取 使用字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        //5.获取socket关联的输出流 将数据写入数据通道
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,client,字符流");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        //6.关闭流和socket
        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();
    }
}
package com.socket;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketTCP03Client {
    public static void main(String[] args) throws IOException {
        //1.连接服务器端
        //连接本机的9999端口,如果连接成功,返回Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端返回socket="+socket.getClass());
        //2.连接上后,生成socket
        OutputStream outputStream = socket.getOutputStream();
        //3.获取socket关联的输出流 将数据写入数据通道
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,server,字符流");
        bufferedWriter.newLine();//插入一个换行符,表示写入内容结束,要求对方使用newLine()
        bufferedWriter.flush();//如果使用字符流,需要手动刷新,否则数据不会写入数据通道
        //4.获取socket关联的输入流 读取服务端写入到数据通道的数据
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        //5.关闭流对象和socket
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        System.out.println("客户端退出");
    }
}

TCP字符流编程_第2张图片TCP字符流编程_第3张图片

总结:字符流写完数据后需要加上bufferedWriter.newLine()代表写数据结束,并且加上bufferedWriter.flush()刷新数据,才会写进成功,字符流读取数据需要使用bufferedReader.readLine()

你可能感兴趣的:(网络编程,服务器,运维)