我正在尝试在我的应用程序和服务器之间设置套接字。我希望我的应用程序从EditText接收用户输入并将其发送到服务器。服务器工作正常。现在,我有一个变量String str,如果我硬编码str为“谁在那里?”,我的应用程序发送“谁在那里?”到服务器,服务器成功接收它。但是如果我尝试使用String str = et.getText()。toString();它不会向我的服务器发送任何内容,无论其价值是多少。以下是我的适用代码。
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="onClick"
android:text="Send" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/myButton"
android:layout_alignLeft="@+id/textView1"
android:ems="10"
android:inputType="text"
android:text="Who's there?" />
MainActivity.java
package com.example.mytest;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5001;
private static final String SERVER_IP = "SERVER_ADDRESS (Assume this is correct)";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
TextView tv = (TextView) findViewById(R.id.textView1);
//This is where the problem is!
//EditText et = (EditText) findViewById(R.id.editText1);
//String str = et.getText().toString();
String str = "Who's there?";
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//Send "str" to server
out.println(str);
//Get string from server NOT WORKING EITHER
String in_str = in.readLine();
tv.setText(in_str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} 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);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
有什么想法吗?
谢谢。