java 使用套接字发送和接收字节[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4860590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:22:07  来源:igfitidea点击:

Sending and receiving byte[] using socket

java

提问by Damir

I have Socket socket=new Socket(ipAddress, port);in my code. I need to send byte[]and receive byte[]over that socket. How to do that, what wrappers to use (I always send byte[]and receive byte[])?

Socket socket=new Socket(ipAddress, port);在我的代码。我需要通过该套接字发送byte[]和接收byte[]。如何做到这一点,使用什么包装器(我总是发送byte[]和接收byte[])?

回答by dogbane

Take a look at the tutorial on Reading from and Writing to a Socket.

查看有关从 Socket 读取和写入 Socket的教程。

To write a byte array to a socket you would:

要将字节数组写入套接字,您需要:

byte[] message = ...;
Socket socket=new Socket(ipAddress, port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Similarly, to read, you would use socket.getInputStream.

同样,要阅读,您将使用socket.getInputStream.

回答by Michael Borgwardt

You don't need wrappers. Just call getInputStream()and getOutputStream()on the socket object. The returned objects have read(byte[])and write(byte[])methods. Be careful to take the return value of read(byte[])into account (it returns the number of bytes actuallyread).

你不需要包装器。只需在套接字对象上调用getInputStream()getOutputStream()。返回的对象有read(byte[])write(byte[])方法。小心考虑返回值read(byte[])(它返回实际读取的字节数)。

回答by sarnold

On the server side, create a new ServerSocketand call accept()on the socket object to accept incoming connections. (You may wish to handle the newly connected session in a new thread to avoid blocking the main thread.)

在服务器端,创建一个新的ServerSocket并调用accept()套接字对象以接受传入的连接。(您可能希望在新线程中处理新连接的会话以避免阻塞主线程。)

On the client side, create a new Socketand call connect()with the server's address and port to initiate the connection.

在客户端,创建一个 newSocketconnect()使用服务器的地址和端口调用以启动连接。

回答by wahid

Use this

用这个

public static byte[] sendandrecive(byte[] message)
{
    byte[] real = null;

    try
    {
        Socket s=new Socket("192.9.200.4",2775);
        DataInputStream dis=new DataInputStream(s.getInputStream());  
        DataOutputStream dout=new DataOutputStream(s.getOutputStream());  

        dout.write(message, 0, message.length);
        dout.flush();  

        //dout.close();  

        byte[] data = new byte[1000];
        int count = dis.read(data);
        real =new byte[count+1];
        for(int i=1;i<=count;i++)
        real[i]=data[i];

        s.close();
        System.out.println("ok");

        }

    catch(Exception e)
    {
        System.out.println(e);
    }
    return real;  
}