我有一台服务器,如果我使用node.js和javascript,我会完美地连接到它并接收消息。
我在Android Studio上启动了一个具有EditText
和TextView
属性的应用。
我的目标是输入EditText
按发送并将该消息发送到服务器并在TextView
中打印回复。
出于某种原因,我无法让它工作,我可以看到Socket
在我调试它时会连接。但我似乎无法从我的js示例中获得服务器的响应。
这是我的代码:
public class MainActivity extends AppCompatActivity {
private Socket socket;
String response = "";
BufferedReader in = null;
PrintStream out = null;
TextView tv;
EditText et;
private static final int SERVERPORT = 80;
private static final String ONLY_HOST = "myServer.azurewebsites.net";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
et = (EditText) findViewById(R.id.messages);
ClientThread client = new ClientThread();
client.execute();
}
class ClientThread extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(ONLY_HOST, SERVERPORT);
byte[] buffer = new byte[1024];
InputStream inputStream = socket.getInputStream();
while (inputStream.read(buffer) != -1) {
response += new String(buffer);
}
} catch (UnknownHostException e1) {
Log.e("UnknownHost","Socket not starting" );
e1.printStackTrace();
} catch (IOException e1) {
Log.e("IO Exception","Socket not starting" );
e1.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (tv != null) {
tv.setText(response);
}
super.onPostExecute(result);
}
}
public void sendIt(View v) {
try {
if (socket.isConnected()) {
out = new PrintStream(socket.getOutputStream(), true);
out.write(et.getText().toString().getBytes());
out.flush();
}
} catch (UnknownHostException e1) {
Log.e("sendIt","1st" );
e1.printStackTrace();
} catch (IOException e1) {
Log.e("sendIt","2nd" );
e1.printStackTrace();
}
}
}
任何帮助都会让我已经这么久了。
谢谢!