我正在尝试通过套接字在我的计算机上运行的 android 应用程序(它将作为客户端)和 java 应用程序(作为服务器)之间创建通信。虽然我的应用程序非常简单,但它在我的 Android 设备上崩溃了。 谁能帮我???我将报告以下代码 fragment ..
服务器端
public class Server {
public static void main(String args[]){
try {
ServerSocket ss=new ServerSocket(9090);
Socket client=ss.accept();
System.out.println("A request is arrived");
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
PrintWriter out=new PrintWriter(oos,true);
out.write("Hello..I'm the Server");
out.flush(); out.close(); client.close();
} catch(Exception e){e.printStackTrace();}
}
}
客户端
public class ChildActivity extends Activity{
public static final int SERVERPORT = 9090;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
InetAddress addre=InetAddress.getByName("a.b.c.d"); //ip address got typing command ipconfig in windows
Socket socket=new Socket(addre,9090);
ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
String msg=(String) in.readObject();
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
in.close();
} catch (Exception e) {e.printStackTrace();}
}
}
});... and so on }}
我还在文件 list 中添加了以下权限,因为我的手机通过 wi-fi 连接到互联网。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
非常感谢您的各种帮助...再次感谢。 附注对不起我的英语:P
最佳答案
我会尝试猜测你的崩溃日志。你有一个 android.os.NetworkOnMainThreadException。
这个答案应该对您有帮助https://stackoverflow.com/a/6343299/1173794
关于java - 通过套接字连接 Android 应用程序(作为客户端)和在我的机器上运行的应用程序(作为服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458357/