在我的代码中我有 Socket socket=new Socket(ipAddress, port);
, 我需要通过这个socket发送byte[]
并接收byte[]
. 那么如何做到呢?我该使用哪些封装器(我总是发送byte[]
和 接收byte[]
)?
在我的代码中我有 Socket socket=new Socket(ipAddress, port);
, 我需要通过这个socket发送byte[]
并接收byte[]
. 那么如何做到呢?我该使用哪些封装器(我总是发送byte[]
和 接收byte[]
)?
byte[] message = ...;
Socket socket=new Socket(ipAddress, port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);
类似地,要进行读取操作,您需要使用socket.getInputStream
方法。
getInputStream()
和 getOutputStream()
。返回的对象具有 read(byte[])
和 write(byte[])
方法。请注意考虑 read(byte[])
的返回值(它返回实际读取的字节数)。ServerSocket
并在套接字对象上调用 accept()
来接受传入连接。(您可能希望在新线程中处理新连接的会话,以避免阻塞主线程。)Socket
并使用服务器的地址和端口调用 connect()
来启动连接。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;
}