在android两个仿真器中使用套接字进行客户机-服务器通信
我在尝试连接两个android模拟器时出错 首先,我运行客户端仿真器5554,然后运行服务器仿真器5556 另一面写着:在android两个仿真器中使用套接字进行客户机-服务器通信,android,sockets,client-server,Android,Sockets,Client Server,我在尝试连接两个android模拟器时出错 首先,我运行客户端仿真器5554,然后运行服务器仿真器5556 另一面写着: telnet localhost 5554 redir add tcp:5000:6000 在我点击客户端的发送按钮后,我得到了一个没有响应的错误 我的代码: 服务器 package com.example.socketserver; import java.io.DataInputStream; import java.io.DataOutputStream; impo
telnet localhost 5554
redir add tcp:5000:6000
在我点击客户端的发送按钮后,我得到了一个没有响应的错误
我的代码:
服务器
package com.example.socketserver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textIn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (TextView)findViewById(R.id.textView1);
}
public void Start(View v) throws IOException{
Socket socket = null;
ServerSocket serverSocket = new ServerSocket(6000);
socket = serverSocket.accept();
DataInputStream dataInputStream = null;
dataInputStream = new DataInputStream(socket.getInputStream());
textIn.setText(dataInputStream.readUTF());
//Toast.makeText(this, "Listening...", Toast.LENGTH_SHORT).show();
TextView label=(TextView)findViewById(R.id.textView3);
label.setText("Loading...");
serverSocket.close();
}
@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;
}
}
客户
package com.example.socketclient;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class ClientActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
}
public void Send(View v) throws IOException{
Socket socket = null;
socket = new Socket("10.0.2.2", 5000);
DataOutputStream dataOutputStream = null;
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("Message from Sender");
if (socket != null){
socket.close();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
}
你能发日志吗?你把权限放在android清单上了吗?是06-09 17:39:00.827:E/ActivityManager(849):13%总计:6.8%用户+6.8%内核