android客户端使用socket连接本机进行通信
android做的客户端,连接本地,在socket连接的地方报错,各位知道怎么回事吗?
代码:android端:
package com.android;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class NetworkClientActivity extends Activity {
private TextView myTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myTextView=(TextView)findViewById(R.id.msgTextView01);
myTextView.setText("dd");
try {
Socket socket=new Socket("192.168.1.115",10000);
InputStream in=socket.getInputStream();
byte[]buffer=new byte[in.available()];
in.read(buffer);
String msg=new String(buffer);
myTextView.setText(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端:
package com.server;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Myserver {
public static void main(String[] args) {
try {
ServerSocket server=new ServerSocket(10000);
while(true){
Socket client=server.accept();
OutputStream out=client.getOutputStream();
String msg="Hello android";
out.write(msg.getBytes());
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
[解决办法]
记得 要在xml 开启网络的连接的权限哈 亲~