基本模型 : Client、Server
基本概念 : 兩個進程之間相互通訊,然後其中一個必須提供固定的位置,而另一個端
只需要知道這個固定的位置,並去建立兩者之間的聯繫。固定位置的被稱
為伺服器;建立聯繫的被稱為客戶端。
Control.java
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import javax.net.SocketFactory;
import android.util.Log;
public class Control {
private static String host;
private static int port;
private static int timeout = 3000;
private static PrintWriter mOutput;
public Control(String host, int port){
Control.host = host;
Control.port = port;
}
public void send(String mess, ControlCallback controlCallback){
new Send(mess, controlCallback).start();
}
//發送訊息
private static class Send extends Thread {
final String action;
public Send(String action) {
this.action = action;
}
public void run() {
try{
Socket socket = SocketFactory.getDefault().createSocket();
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.connect(remoteaddr, timeout);
Log.d("tag","running!!! Host : "+host+" port : "+port);
mOutput = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
mOutput.println(action);
Log.d("tag","Link success");
}catch(ConnectException e){
Log.d("tag","Fail !! ConnectException : "+e.getMessage());
}catch(Exception e){
Log.d("tag","Fail !! Exception : "+e.getMessage());
}
};
}
}
記得要加入權限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
歡迎轉載,請註明出處。
作者已經移除這則留言。
回覆刪除我跑的時候出現:ControlCallback cannot be resolved to a type?
刪除