我的TCP客户端出了问题。 我的TCP服务器将一个位图作为字符串发送到TCP客户端。目前每秒有15 bmp。我的问题是,当我将接收到的字节数组转换为字符串时,大多数都被读为“////// ....”。
我的TCP服务器代码是(C#):
private void StreamWriter(byte[] writeMessage)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(Ip), Port);
NetworkStream streamSender = client.GetStream();
streamSender.Write(writeMessage, 0, writeMessage.Length);
streamSender.Flush();
streamSender.Close();
client.Close();
}
private void sendImage()
{
while (send)
{
MemoryStream mem = new MemoryStream();
image.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
mem.Close();
mem.Dispose();
StreamWriter(Encoding.ASCII.GetBytes(Convert.ToBase64String(mem.ToArray())));
i++;
}
}
我的客户端代码是(Android Studio):
class MyServerThread implements Runnable {
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedInputStream bufferedReader = new BufferedInputStream(is);
byte[] contents = new byte[440000];
int bytesRead = 0;
while ((bytesRead = bufferedReader.read(contents)) != -1) {
message = new String(contents, 0, bytesRead);
}
is.close();
bufferedReader.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我找到了解决方案。
现在是客户端代码:
class MyServerThread implements Runnable {
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
message = total.toString();
s.close();
is.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}