I have 2 sockets connecting and sending a file. I want at some point send a signal to the second socket. I thought of sending a string "start" and when the receiver socket gets it, I execute something. Below is the code for receiver and sender. What am I doing wrong? The receiver never gets the "start" and I am sure its being sent. Thanks
Sender Side:
byte[] buff = new byte[1024 * 50];
while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
client.getOutputStream().write(buff, 0, readBytes);
if(sendStart){
client.getOutputStream().("start".getBytes("UTF-8"), 0, "start".getBytes("UTF-8").length);
sendStart = false;
}
}
Receiver Side:
DataInputStream in = null;
try {
in = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
}
byte buffer[] = new byte[1024 * 50];
while ((len = in.read(buffer)) != -1) {
String received = new String(buffer, "UTF-8");
if(received!=null && received.equals("start")){
Log.d(TAG,"received start");
//do something
}
receivedFile.write(buffer, 0, len);
}
答案 0 :(得分:0)
我认为错误可能在这里:
client.getOutputStream().("start".getBytes("UTF-8"), 0, "start".getBytes("UTF-8").length);
如果你看,write()
方法不在这一行的任何地方。
另外,我想问一下,您是否有一个特殊原因要自己处理字符串序列化?您可以使用PrintWriter
和Scanner
之类的字符串,也可以将ObjectOutputStream
和ObjectInputStream
用于任何类型的对象。