[問題] client持續接收字串
正在練習手機與手機間使用網路傳輸字串
拿一台手機當作server
另一台當作client
client能順利連接到server
而server能傳送字串到client
但當server想要傳輸兩次以上的字串給client
就無法成功了
以下是其中client的程式碼(我是寫在一個button的觸發事件中)
mButton2.setOnClickListener(new View.OnClickListener() //輸入ip連線
{
public void onClick(View v)
{
String address =
(((EditText) findViewById(R.id.EditText01)).getText().toString());// 連線的ip
int port = 1234;// 連線的port
try {
serverip = InetAddress.getByName(address);
clientsocket = new Socket(serverip,port);
receive_word();
}catch(Exception e){TextView3.setText("Net connection is
fail.");}
});
private void receive_word()
{
try{
InputStream in=clientsocket.getInputStream(); //接收字串
byte data2[] = new byte[1024];
String temp2 = "";
int length=0;
//length=in.read(data2);
while((length=in.read(data2)) != -1)
{
temp2+= new String(data2, 0, length);
TextView3.setText(temp2);
}
//temp2+= new String(data2, 0, length);
//TextView3.setText(temp2);
}catch(Exception e){TextView3.setText("失敗");}
}
基本上建立連線這個確定是沒問題的
但就是無法接收server傳出來的字串
如果將receive_word()中的while拿掉
改為while上下三行//的程式碼的話
接收單次字串也是沒問題的
但就不知道為什麼想要多次接收字串(使用while)就有問題
socket和inputstream都沒有close
是while使用錯誤嗎?還是因為建立在按鍵事件中?
還是說多次接收字串需要其他的方法?
希望各位可以幫我解答
謝謝!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.117.169.50
推
09/12 17:21, , 1F
09/12 17:21, 1F
→
09/12 17:32, , 2F
09/12 17:32, 2F
推
09/12 17:48, , 3F
09/12 17:48, 3F
推
09/14 18:38, , 4F
09/14 18:38, 4F
→
09/14 18:39, , 5F
09/14 18:39, 5F
→
09/14 18:40, , 6F
09/14 18:40, 6F