[英]Unable to send message from PC and mobilephone using socket communication
這是我的任務:使用套接字通信連接PC和手機。我在通過套接字連接輸入消息時遇到問題。 我使用eclipse從PC到手機運行程序。 我在文本框中輸入文字。 當我按下發送按鈕時,我無法發送文本並使其反映在手機上。 程序代碼不再有錯誤。 這是我獲得的代碼鏈接: http : //android-er.blogspot.sg/2011/01/simple-communication-using.html
這些是我的代碼,沒有錯誤:
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.socket_client);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.217.137.207", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
從代碼中看來,您正在嘗試打開具有給定IP [10.217.137.207]的設備到外部設備的套接字連接。
僅當您使用要測試的設備的ip時,此代碼才有效。 嘗試使用127.0.0.1
dataInputStream.readUTF();
僅當從具有IP [10.217.137.207]的設備寫入內容時,才會返回任何內容。
如果您使用設備的IP地址,則
dataInputStream.readUTF();
將返回您編寫的所有內容
dataOutputStream.writeUTF()
我相信必須清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.