socket 通讯方法

请问有没有什么封装好的socket通讯的方法 请求参数如下

public static byte[] sendAndReceive(String host, int port, byte[] sendBody)

请求参数
String host -- ip
int port -- 端口
byte[] sendBody -- 发送的String 转为byte[]数组

返回参数

byte[] --返回的byte[]数组 之后可以转为String

“Devil组”引证GPT后的撰写:
以下是一个使用Java Socket实现的sendAndReceive方法

import java.io.*;
import java.net.*;

public class SocketUtils {

    public static byte[] sendAndReceive(String host, int port, byte[] sendBody) throws IOException {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            // 创建Socket对象,并连接到指定的主机和端口
            socket = new Socket(host, port);
            // 获取输出流,用于向服务器发送数据
            outputStream = socket.getOutputStream();
            outputStream.write(sendBody);
            // 刷新输出流,确保所有数据都已经被发送出去
            outputStream.flush();
            // 获取输入流,用于读取服务器返回的数据
            inputStream = socket.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            // 读取数据并写入到ByteArrayOutputStream中
            while ((length = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            // 返回ByteArrayOutputStream中的字节数组
            return byteArrayOutputStream.toByteArray();
        } finally {
            // 关闭所有资源
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        }
    }
}


方法会创建一个Socket对象,并连接到指定的主机和端口。然后,将发送的数据写入到Socket的输出流中,并通过刷新输出流确保数据已被发送。接着,使用Socket的输入流读取服务器返回的数据,并将其写入到ByteArrayOutputStream中。最后,将ByteArrayOutputStream中的字节数组作为返回值返回给调用者。

小魔女参考了bing和GPT部分内容调写:
是的,有封装好的socket通讯的方法,请求参数如下:

public static byte[] sendAndReceive(String host, int port, byte[] sendBody)

其中:

String host -ip:表示要连接的主机的IP地址;

int port:表示要连接的端口号;

byte[] sendBody:表示要发送的字节数组,可以先将String转换为字节数组;

返回参数:

byte[]:表示接收到的字节数组,可以将其转换为String。

下面是一段示例代码:

public static byte[] sendAndReceive(String host, int port, byte[] sendBody) {
    try {
        Socket socket = new Socket(host, port);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(sendBody);
        outputStream.flush();
        InputStream inputStream = socket.getInputStream();
        byte[] receiveBody = new byte[1024];
        inputStream.read(receiveBody);
        socket.close();
        return receiveBody;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

回答不易,记得采纳呀。

该回答引用ChatGPT

在Java中,您可以使用java.net.Socket类来创建和管理TCP套接字。在Spring框架中,您可以使用Spring的org.springframework.integration.ip.tcp.TcpOutboundGateway和org.springframework.integration.ip.tcp.TcpInboundGateway类来实现TCP通信。

以下是使用Java Socket类实现的sendAndReceive方法:


public static byte[] sendAndReceive(String host, int port, byte[] sendBody) throws IOException {
    Socket socket = new Socket(host, port);
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();
    outputStream.write(sendBody);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        byteArrayOutputStream.write(buffer, 0, length);
    }

    socket.close();
    return byteArrayOutputStream.toByteArray();
}

这个方法会向指定的主机和端口发送数据,然后等待接收数据并将其存储为字节数组,最后返回字节数组。如果发生任何错误,它将抛出IOException异常。

要使用Spring的TcpOutboundGateway和TcpInboundGateway类实现相同的功能,请参考Spring Integration的文档和示例。


public static byte[] sendAndReceive(String host, int port, byte[] sendBody) {
    //创建Socket
    Socket socket = new Socket(host, port);
    //获取输出流
    OutputStream outputStream = socket.getOutputStream();
    //发送输出流
    outputStream.write(sendBody);
    //获取输入流
    InputStream inputStream = socket.getInputStream();
    //定义缓冲区
    byte[] buffer = new byte[1024];
    //定义接收长度
    int len = 0;
    //读取输入流
    len = inputStream.read(buffer);
    //关闭输入输出流
    outputStream.close();
    inputStream.close();
    socket.close();
    //将读取的输入流转换为byte[]数组
    byte[] data = new byte[len];
    System.arraycopy(buffer, 0, data, 0, len);
    return data;
}

参考GPT和自己的思路:可以使用Java的Socket类来进行Socket通讯,下面是一个简单的示例代码:

import java.net.*;
import java.io.*;

public class SocketUtils {
    
    public static byte[] sendAndReceive(String host, int port, byte[] sendBody) throws IOException {
        // 创建Socket连接
        Socket socket = new Socket(host, port);
        
        // 发送请求数据
        OutputStream out = socket.getOutputStream();
        out.write(sendBody);
        out.flush();
        
        // 接收响应数据
        InputStream in = socket.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        
        // 关闭连接
        in.close();
        out.close();
        socket.close();
        
        // 返回响应数据
        return bos.toByteArray();
    }
}

其中,sendAndReceive方法接收三个参数,分别是host、port和sendBody,表示需要连接的目标主机、端口号和发送的数据。该方法会返回一个byte数组,表示接收到的响应数据。可以通过将该byte数组转换为字符串来获取具体的响应内容。

需要注意的是,该方法可能会抛出IOException异常,需要在调用时进行处理。

参考


import java.net.*;
import java.io.*;

public class SocketUtils {
    
    public static byte[] sendAndReceiveBysock(String host, int port, byte[] sendBody) throws IOException {
        // 此处创建Socket连接
        Socket socket = new Socket(host, port);
        
        // 发送请求数据
        OutputStream out = socket.getOutputStream();
        out.write(sendBody);
        out.flush();
        
        // 接收响应数据
        InputStream in = socket.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        
        // 关闭连接
        in.close();
      //关闭流
        out.close();
     // 关闭socket
        socket.close();
        
        // 返回响应数据
        return bos.toByteArray();
    }
}

SocketClient类构造host、port、timeOut
package com.skyon.credit.socket;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SocketClient {

    private SocketClientBean socketClientBean;

    /**
     * 指定服务器地址、端口和超时时间的构造器
     * @param host
     * @param port
     * @param timeOut
     */
    public SocketClient(String host,int port,int timeOut) throws Exception{
        log.info("当前访问的主机IP:[{}]-端口:[{}]", host, port);
        socketClientBean = new SocketClientBean(host, port, timeOut);
        socketClientBean.bindSocket();
    }
    
    /**
     * 指定服务器地址、端口构造器
     * @param host
     * @param port
     * @throws Exception
     */
    public SocketClient(String host,int port) throws Exception{
        log.info("当前访问的主机IP:[{}]-端口:[{}]", host, port);
        socketClientBean = new SocketClientBean(host, port);
        socketClientBean.bindSocket();
    }
    
    /**
     * 发送消息
     * @param sendMsg
     * @return
     * @throws Exception
     */
    public byte[] sendMsg (byte[] sendMsg) throws Exception {
        socketClientBean.sendTcpMsg(sendMsg);
        byte[] receiveMsg = socketClientBean.receiveTcpMsg();
        socketClientBean.closeSocket();
        return receiveMsg;
    }
}


/************************************************************/
SocketClientBean类获取输入输出流关闭资源
package com.skyon.credit.socket;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

public class SocketClientBean {

    // 客户端socket
    private Socket socket;
    // 从socket获得的输出流
    private DataOutputStream outputStream;
    // 从socket获得的输入流
    private DataInputStream inputStream;
    // byte数组输出流
    private ByteArrayOutputStream byteArrayOutputStream;
    // 请求IP
    private String hostName;
    // 请求端口
    private int hostPort;
    // 超时时间
    private int timeOut;

    /**
     * 空构造器
     */
    public SocketClientBean() {
        timeOut = 60000;
        this.byteArrayOutputStream = new ByteArrayOutputStream();
    }

    /**
     * 指定服务器地址和端口的构造器
     * @param hostName
     * @param hostPort
     */
    public SocketClientBean(String hostName, int hostPort){
        this.hostName = hostName;
        this.hostPort = hostPort;
        this.timeOut = 60000;
        this.byteArrayOutputStream = new ByteArrayOutputStream();
    }

    /**
     * 指定服务器地址、端口和超时时间的构造器
     * @param hostName
     * @param hostPort
     * @param timeOut
     */
    public SocketClientBean(String hostName, int hostPort, int timeOut){
        this.hostName = hostName;
        this.hostPort = hostPort;
        if (timeOut > 0) {
            this.timeOut = timeOut;
        }else {
            this.timeOut = 60000;
        }
        this.byteArrayOutputStream = new ByteArrayOutputStream();
    }

    /**
     * 
     * 建立Socket连接并创建输入输出流
     *
     */
    public void bindSocket () throws Exception {
        socket = new Socket(hostName,hostPort);
        outputStream = new DataOutputStream(socket.getOutputStream());
        inputStream = new DataInputStream(socket.getInputStream());
        socket.setSoTimeout(timeOut);
    }

    /**
     * 
     * 发送消息
     *
     */
    public void sendTcpMsg (byte[] bytes) throws Exception {
        outputStream.write(bytes);
        outputStream.flush();
    }

    /**
     * 
     * 接收响应
     *
     */
    public byte[] receiveTcpMsg () throws Exception {
        byteArrayOutputStream = new ByteArrayOutputStream();
        inputStream = new DataInputStream(socket.getInputStream());
        byte[] b = new byte[1];
        while(-1 != (inputStream.read(b))) {
            if(b[0] == '\n')
                break;
            else
                byteArrayOutputStream.write(b);
        }
        if(byteArrayOutputStream.size() == 0) return null;
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 
     * 关闭资源
     *
     */
    public void closeSocket() {
        try{
            if(outputStream != null) {
                outputStream.close();
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
            if(inputStream != null) {
                inputStream.close();
            }
            if(socket!=null) {
                socket.close();
            }
        }catch(Exception e){

        }
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public int getHostPort() {
        return hostPort;
    }

    public void setHostPort(int hostPort) {
        this.hostPort = hostPort;
    }

    public int getTimeOut() {
        return timeOut;
    }

    public void setTimeOut(int timeOut) {
        this.timeOut = timeOut;
    }
}



/******************************************************************/
SocketClientServiceImpl类


package com.skyon.credit.socket;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.skyon.credit.enums.BaseCodeEnum;
import com.skyon.credit.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Socket 客户端
 * @author GH
 *
 */
@Slf4j
@Component
public class SocketClientServiceImpl implements SocketClientService{
    
    @Value("${socket.client.timeOut}")
    private int timeOut;
    
    private SocketClient socketClient;
    
    /**
     * 发送消息
     */
    @Override
    public byte[] socketRequest(String host, int port, byte[] sendMsg) {
        try {
            socketClient = new SocketClient(host, port, this.timeOut);
            byte[] receiveMsg = socketClient.sendMsg(sendMsg);
            return receiveMsg;
        }catch (Exception e) {
            log.error("访问的主机IP:[{}]-端口:[{}]-Socket通信异常信息:", host, port, e);
            throw new BaseException(BaseCodeEnum.SOCKET_CONNECTION_EXCEPTION);
        }
    }
    
}


Java中提供了Socket和ServerSocket类来实现基于TCP协议的Socket通信,但是它们并没有提供直接的sendAndReceive方法来实现发送和接收数据,需要自己封装方法实现。下面是一个简单的封装示例:


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketUtil {
    public static byte[] sendAndReceive(String host, int port, byte[] sendBody) {
        byte[] receiveBody = null;
        Socket socket = null;
        try {
            // 创建Socket连接
            socket = new Socket(host, port);
            // 发送数据
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(sendBody);
            outputStream.flush();
            // 接收数据
            InputStream inputStream = socket.getInputStream();
            receiveBody = new byte[1024];
            int len = inputStream.read(receiveBody);
            receiveBody = len > 0 ? new String(receiveBody, 0, len).getBytes() : null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭Socket连接
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return receiveBody;
    }
}

这个示例中使用了Java提供的Socket和InputStream/OutputStream类来进行数据的发送和接收。在发送数据时,先获取Socket的输出流,然后写入要发送的数据,最后flush一下确保数据被立即发送。在接收数据时,先获取Socket的输入流,然后读取数据并存储到byte数组中。注意,读取数据时可能会出现阻塞,需要根据具体情况进行优化。
使用示例:

String host = "127.0.0.1";
int port = 8080;
byte[] sendBody = "Hello World!".getBytes();
byte[] receiveBody = SocketUtil.sendAndReceive(host, port, sendBody);
String result = receiveBody != null ? new String(receiveBody) : null;
System.out.println("收到服务器返回的数据:" + result);

在实际使用时,需要根据具体情况进行优化和封装。例如,可以添加超时时间、重试次数等功能,以提高代码的健壮性。