Sending and receiving byte[] using socket
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 wrapper开发者_运维问答s to use (I always send byte[]
and receive byte[]
)?
Take a look at the tutorial on Reading from and Writing to a 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
.
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 actually read).
On the server side, create a new ServerSocket
and 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.)
On the client side, create a new Socket
and call connect()
with the server's address and port to initiate the connection.
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;
}
精彩评论