Java 正在尝试制作android TCP服务器应用程序
我正在尝试制作一个android TCP服务器应用程序,它可以通过wifi屏蔽从我的arduino板获取消息 我是java编码的新手,所以我从 但它似乎不起作用。它没有任何错误,但当我运行它时,它没有响应 有人能帮我吗? 包com.example.androidserversocketJava 正在尝试制作android TCP服务器应用程序,java,android,sockets,tcp,Java,Android,Sockets,Tcp,我正在尝试制作一个android TCP服务器应用程序,它可以通过wifi屏蔽从我的arduino板获取消息 我是java编码的新手,所以我从 但它似乎不起作用。它没有任何错误,但当我运行它时,它没有响应 有人能帮我吗? 包com.example.androidserversocket package roman10.tutorial.tcpcommserver; package roman10.tutorial.tcpcommserver; import java.io.BufferedRe
package roman10.tutorial.tcpcommserver;
package roman10.tutorial.tcpcommserver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class TcpServer extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textDisplay = (TextView) this.findViewById(R.id.text1);
textDisplay.setText("");
runTcpServer();
}
private TextView textDisplay;
private static final int TCP_SERVER_PORT = 5000;
private void runTcpServer() {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpServer", "received: " + incomingMsg);
textDisplay.append("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.i("TcpServer", "sent: " + outgoingMsg);
textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
就我而言,
onCreate()
方法将在UI线程上调用。不再能够在UI线程上运行网络操作。因此,您应该替换
runTcpServer();
与
您还需要向AndroidManifest.xml添加以下行
<uses-permission android:name="android.permission.INTERNET" />
如果你还没有这样做
您可以找到有关该问题的更多信息
<uses-permission android:name="android.permission.INTERNET" />