程序A的代码示例:

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class ProgramA {
    public static void main(String[] args) {
        try {
            // 创建Socket对象,连接到程序B的IP地址和端口号
            Socket socket = new Socket("程序B的IP地址", 程序B的端口号);
            
            // 获取输出流
            OutputStream outputStream = socket.getOutputStream();
            
            // 发送数据
            String data = "hello world!";
            outputStream.write(data.getBytes());
            
            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

程序B的代码示例:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ProgramB {
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象,监听指定端口号
            ServerSocket serverSocket = new ServerSocket(程序B的端口号);
            
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            
            // 获取输入流
            InputStream inputStream = socket.getInputStream();
            
            // 读取数据
            byte[] buffer = new byte[1024];
            int length = inputStream.read(buffer);
            String data = new String(buffer, 0, length);
            
            // 处理数据
            System.out.println("Received data from ProgramA: " + data);
            
            // 返回响应
            String response = "ok";
            socket.getOutputStream().write(response.getBytes());
            
            // 关闭连接
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意替换代码中的 "程序B的IP地址" 和 "程序B的端口号" 为实际的IP地址和端口号。

程序A通过socket发送数据 hello world! 到程序B返回 ok 到 程序 Ajava

原文地址: https://www.cveoy.top/t/topic/i63T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录