我写了一个类,我可以通过套接字发送和接收数据。在本课程中,首先,我使用特定的端口和IP连接到套接字,然后初始化outputstrem和inputstram。
我可以轻松发送和接收数据,但只有在我这边有请求时才能接收数据。有时我必须在不发送数据的情况下接收新信息。
如何在不发送数据的情况下接收数据(侦听套接字(?
public class INetConnection{
private DataOutputStream outputStream;
private DataInputStream inputStream;
private Callback mCallback;
private Socket socket;
private byte[] rec_buffer;
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public void connectToNetwork() {
if (socketConnect()) {
try {
outputStream = new DataOutputStream(getSocket()
.getOutputStream());
inputStream = new DataInputStream(getSocket().getInputStream());
Log.i("Log", "Streams Created!");
receiveData();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean socketConnect() {
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
Log.i("Socket", "Connection stablished");
return true;
} catch (UnknownHostException e) {
Log.d("Exception mode", "UnknownHostException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Exception mode", "IOException");
e.printStackTrace();
}
return false;
}
public void sendData(final byte[] data) {
outputStream.write(data, 0, data.length);
}
private void receiveData(){
// Again, probably better to store these objects references in the support class
if(getSocket() != null && getSocket().isConnected()){
try {
Log.i("Log", "Ready to receive!");
byte[] buffer = new byte[265536];
int size = 0;
while ((size = inputStream.read(buffer)) != -1){
Log.i("Log", "Data's been read fully from server");
rec_buffer = new byte[size];
rec_buffer = Arrays.copyOfRange(buffer, 0 , size);
for (int i = 0; i< size; i++)
Log.i("Log", "Data i: " + rec_buffer[i]);
}
} catch (IOException e) {
Log.e("Log", "Error occured during receiving data");
e.printStackTrace();
}
}
}
}
您通过套接字连接到的服务器是您自己的服务器,还是其他人的服务器?
通常,服务器的行为方式是仅在请求时发送数据(至少 REST API 是这样运行的(。但是,如果这是您自己的服务器,则可以将其设置为一旦连接套接字,它将开始向客户端发送数据。这样,客户端上的输入流应该能够在不发送任何内容的情况下接收数据。
如果服务器不是您的修改,并且希望客户端首先发送请求,那么我想除了先从客户端发送数据之外,您无能为力。