我是android的新手程序员......我需要帮助 通过wifi在两部手机之间发送文字 第一:服务器 第二:客户 我正在寻找更多,但我需要简单的代码,并且很容易帮助我 thnx for advance
答案 0 :(得分:1)
我猜插座就是你要找的......
客户端示例:
private final String IP = "9.9.9.9";
private final int PORT = 8080;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new MainThread()).start();
}
class MainThread implements Runnable {
@Override
public void run() {
try {
InetAddress address = InetAddress.getByName(IP);
socket = new Socket(address,PORT);
new Thread(new GetThread()).start();
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class GetThread implements Runnable {
@Override
public void run() {
try {
InputStreamReader isR=new InputStreamReader(socket.getInputStream());
BufferedReader bfr=new BufferedReader(isR);
while(true) {
String textMessage = bfr.readLine();
// TODO: Insert logic which use the recived message (textMessage)
}
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
在线程中,套接字正在等待发送数据(while(true))。
并且IP是服务器的IP(如果您连接到计算机
)使用wifi,您应该在命令行中使用ipconfig检查您的IP地址。)