美文网首页
自定义服务器so

自定义服务器so

作者: simplerandom | 来源:发表于2020-07-01 17:09 被阅读0次

server

public class Server {
    public static void main(String[] args) throws IOException, IOException {
        int i = 0;
        String taskId;
        ServerSocket serverSocket = new ServerSocket(6666);
        Socket socket = serverSocket.accept();


        InputStream inputStream = socket.getInputStream();
        Scanner scanner = new Scanner(inputStream);
        System.out.println(scanner.nextLine());


        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.println("hello output");

        // 释放资源
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}

client

public class Client {
    public static void main(String[] args) throws IOException, IOException {
        int i;
        Socket socket = new Socket("localhost", 6666);

        // 写数据到服务器
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("mytask".getBytes());
        // 关闭当前输出流,同时关闭了服务器的输入流(此方法必须要,否则无法正常读写)
        socket.shutdownOutput();

        // 读服务类写来的数据
        InputStream inputStream = socket.getInputStream();
        Scanner scanner = new Scanner(inputStream);
        System.out.println(scanner.nextLine());
        socket.shutdownInput();

        // 释放资源
        outputStream.close();
        inputStream.close();
        socket.close();
    }
}

相关文章

网友评论

      本文标题:自定义服务器so

      本文链接:https://www.haomeiwen.com/subject/aydhqktx.html