Java 代码Socket clientSocket=newsocket();android应用程序崩溃,即使是在单独的线程中
我是Android新手,我研究这个bug已经有一段时间了,但仍然没有弄明白。我试图从智能手机向运行在笔记本电脑上的服务器发送消息。问题在于,由于某种原因,它在创建套接字时崩溃(不是立即而是几秒钟后)。即使我有权限(.INTERNET)并在单独的线程中运行代码,它仍然失败Java 代码Socket clientSocket=newsocket();android应用程序崩溃,即使是在单独的线程中,java,android,sockets,crash,Java,Android,Sockets,Crash,我是Android新手,我研究这个bug已经有一段时间了,但仍然没有弄明白。我试图从智能手机向运行在笔记本电脑上的服务器发送消息。问题在于,由于某种原因,它在创建套接字时崩溃(不是立即而是几秒钟后)。即使我有权限(.INTERNET)并在单独的线程中运行代码,它仍然失败 public class Communcation extends Activity{ private Socket s = null; short REDIRECTED_SERVERPORT = 5000; @Overrid
public class Communcation extends Activity{
private Socket s = null;
short REDIRECTED_SERVERPORT = 5000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_communcation);
final EditText msg = (EditText) findViewById(R.id.etMsg);
Button send = (Button) findViewById(R.id.bSend);
final TextView convo = (TextView) findViewById(R.id.tvConvo);
convo.setText("");
final TextView status = (TextView) findViewById(R.id.tvStatus);
status.setText("");
Button connect = (Button) findViewById(R.id.btnConnect);
final EditText ipaddress = (EditText) findViewById(R.id.address);
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
status.setText("Estabilishing the connection to " + ipaddress.getText().toString());
new Thread() {
public void run() {
try {
s = new Socket(InetAddress.getByName(ipaddress.getText().toString()), REDIRECTED_SERVERPORT);
status.setText("Established connection..");
} catch (IOException e) {
status.setText("Failed the connection" + e.getMessage());
}
}
}.start();
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String message = msg.getText().toString();
new Thread() {
public void run() {
PrintWriter outp = null;
BufferedReader inp = null;
String serverMsg = null;
try {
outp = new PrintWriter(s.getOutputStream(), true);
inp = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (IOException e) {
status.setText("Couldn't initate the buffers ");
}
outp.write(message);
}
}.start();
}
});
}
}
在我的服务器端代码中,我等待连接并打印消息,但从测试代码到目前为止,它从未通过接受部分
while (1)
{ int clientfd;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
/*---accept a connection (creating a data pipe)---*/
printf("[SERVER] Waiting for clients\n");
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
recv(clientfd, buffer, MAXBUF, 0);
printf("[SERVER] Received from the client: [%s]\n", buffer);
/*---Close data connection---*/
close(clientfd);
}
事实上,在这种情况下,没有它我也能说出来。在同一线程上设置文本视图的文本。您只能在UI线程中触摸视图。您需要将Runnable发布到处理程序,或者在UI代码上使用RunNouithRead。发布堆栈跟踪。“代码崩溃”不是问题描述。