socket的使用 | TCP/IP协议下服务器与客户端之间传送数据

服务器端代码:

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

public class theServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999); // 该行代码作用:让服务器监听9999端口
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//        byte[] bytes = new byte[1024];
//        int readLine = 0;
//        while ((readLine = inputStream.read(bytes)) != -1) {
//            System.out.print(new String(bytes, 0, readLine));
//        }
//        socket.shutdownInput();
        String readStr = reader.readLine();
        System.out.println(readStr);

        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
//        outputStream.write("server: hi client".getBytes());
//        socket.shutdownOutput();
        writer.write("server: hi client");
        writer.newLine();
        writer.flush();

        writer.close(); // 后打开的流,先关闭
        reader.close();
        socket.close();
        serverSocket.close(); // 先打开的流,后关闭
    }
}

客户端代码:

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

public class theClient {
    public static void main(String[] args) throws IOException {
        Socket socket =  new Socket(InetAddress.getLocalHost(),9999); // 该行代码作用:让客户端连接到服务器的9999端口

        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
//        outputStream.write("client: hi server".getBytes());
        writer.write("client: hi server");
//        socket.shutdownOutput();
        writer.newLine();
        writer.flush();

        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//        byte[] bytes = new byte[1024];
//        int readLine = 0;
//        while ((readLine = inputStream.read(bytes)) != -1) {
//            System.out.print(new String(bytes, 0, readLine));
//        }
//        socket.shutdownInput();
        String readStr = reader.readLine();
        System.out.println(readStr);

        reader.close();
        writer.close();
        socket.close();
    }
}

运行后结果:

服务器端:
socket的使用 | TCP/IP协议下服务器与客户端之间传送数据_第1张图片
客户端:
socket的使用 | TCP/IP协议下服务器与客户端之间传送数据_第2张图片

你可能感兴趣的:(java,java,socket,服务器,客户端,网络数据传输,tcp/ip)