在我的TCP客户端中,当我的程序处于state = 0时,我收到一条TCP消息我知道我收到的数据是UTF-8并且将收到一条文本消息,所以我将我的数据流存储到:
input = new BufferedReader(new InputStreamReader(dis, "UTF-8"));
当我收到特定的消息,例如“XXX”时,我知道下一条消息将成为BMP文件的一部分。
如何修改输入以接收数据而不将其转换为“UTF-8”?
我的客户的一部分:
public void run() {
mRun = true;
state = ST_RECEIVEMSG;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
dis = new DataInputStream(socket.getInputStream());
// The buffer reader cannot can't wrap an InputStream directly. It wraps another Reader.
// So inputstreamreader is used.
input = new BufferedReader(new InputStreamReader(dis, "UTF-8"));
Log.d("MyApp","We are here");
//in this while the client listens for the messages sent by the server
while (mRun) {
if (state == ST_RECEIVEMSG) {
// The packet contains a message
Log.d("MyApp", "We are here 2");
serverMessage = input.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
}
if ("XXX".equals(serverMessage)) {
// The next message will be the BMP image
Log.d("MyApp", "We are here 4");
state = ST_RECEIVEBMP;
}
} else {
// The packet is part of BMP file
Log.d("MyApp", "We are here 5");
// Save the stream in a file
try {
Log.d("MyApp", "We are here 6");
} catch (Exception e) {
Log.e("TCP", "S: Error at file write", e);
}
}
}
} finally {
socket.close();
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}