我在 Android(客户端)和 C# 应用程序(服务器)之间建立套接字连接以正确读取响应时遇到问题。
我已经成功地收到一条从 android 发送到 c# 的消息,并且我在这方面阅读得很好。但是当我尝试将确认发送回 android 时,我不知道处理这个问题的正确方法,而且我不得不在教程不清楚的地方做出一些假设。我正在在 android 中收到回复,但它不是 100% 正确。我已经通过 Wireshark 验证了 c# 正在发送我想要它发送的内容,并且文本在到达 android 之前看起来很好。
C#:
public void SendClientMessage()
{
NetworkStream clientStream = _Client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!"); //Static test message
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
...
Android:
private void listenResponse()
{
Log.i(TAG, "listenRespose() Listening...");
try
{
InputStream is = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int countBytesRead = bis.read(buffer, 0, 8);
String response = new String(buffer);
Log.i(TAG, "listenResponse() Heard: " + response);
}
catch (IOException e)
{
Log.e(TAG, "listenResponse() IOException", e);
e.printStackTrace();
}
Log.i(TAG, "listenResponse() Done Listening.");
}
...
WireShark shows:
Hello Client!
...
Android LogCat shows:
listenRespose() Listening...
listenResponse() Heard: Hello Cl??????????????????????????? [... ?s continue for a long time]
listenResponse() Done Listening.
如果相反,我像这样初始化我的字符串:
String response = new String(buffer, 0, countBytesRead);
至少我没有得到所有的问号,但我仍然没有得到我应该得到的完整字符串。我是不是初始化了我的 byte[] 错误,或者是否有其他方法可以更好地适合纯文本?
最佳答案
你在这里只读了8个字节
int countBytesRead = bis.read(buffer, 0, 8);
// max bytes to read ^
相反,尽你所能阅读:
int countBytesRead = bis.read(buffer, 0, Buffer.length);
您看到的问号是因为您的缓冲区未初始化。
关于c# - 套接字纯文本响应中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9581023/