![](/img/trans.png)
[英]Android TCP Client can not receive data from TCP Server with wifi
[英]Cant read data from TCP Server with Android Client APP
那是我的Java應用程序中的Java程序。 我試圖與TCP服務器建立TCP連接。 我可以使用其他應用程序連接到服務器,以便可以從tcp服務器發送和接收。 通過我的代碼和程序,我可以很輕松地將消息發送到服務器,但是從服務器接收消息很麻煩。
private Socket socket;
private final int SERVERPORT = 6060;
private final String SERVER_IP = "192.168.0.8";
public TextView tv;
private PrintWriter out;
private InputStream in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
這是我的問題,我不知道如何從服務器接收字符串或字節。 當我在手機上運行我的應用程序時,它會關閉打開的窗口,並說該程序停止工作。 如果我刪除這段代碼(public void ONCLICK2),則可以將消息傳輸到服務器。
public void ONCLICK2(View view) {
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte array[]=new byte[1];
try {
int i=in.read(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
因此,請幫助我處理該部分代碼。 如何接收從TCP服務器發送的字符串。
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
out.println(str);
out.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
簡而言之,問題是您正在截取未知長度的字節數組,並試圖將它們存儲在一個大小為1的數組中。 此外,理想的做法是在數據包中的數據之前附加數據包大小,然后在單獨的線程中創建攔截以等待傳入數據包。
要僅修復您的ONCLICK2,您應該執行以下操作:
byte[] data = new byte[6556];
try {
in = socket.getInputStream();
// NOTE: The data byte array will contain empty values if
// under the size of 6556
int size = in.read(data);
// send to LogCat
Log.e("String", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
我尚未測試此代碼,但這應該可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.