Android使用Socket進行通訊
阿新 • • 發佈:2019-02-06
Java能接受其他通訊實體連線請求的類是ServerSocket,ServerSocket物件用於監聽客戶端的Socket連線,如果沒有連線,它將一直處於等待狀態。
public class SimpleServer {
public static void main(String[] args) {
//建立ServerSocket,用於監聽客戶端Socket的連線請求
try {
ServerSocket ss = new ServerSocket(30000);
while(true)
{
System.out .println("有客戶訪問伺服器");
//每當接受到客戶端Socket的請求時,伺服器端也對應產生一個Socket
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("Helo,這是伺服器返回的訊息!".getBytes("utf-8"));
os.close();
s.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客戶端程式碼
public class MainActivity extends AppCompatActivity {
TextView textView;
Button btn;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.show);
btn = (Button)findViewById(R.id.button);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what)
{
case 0:
Bundle bundle;
bundle = msg.getData();
textView.setText(bundle.getString("result","沒有成功"));
}
}
};
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread()
{
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.what = 0;
Socket socket = null;
try {
socket = new Socket("10.20.0.1",30000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
Bundle bundle = new Bundle();
bundle.putString("result",line);
msg.setData(bundle);
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(msg);
}
}.start();
}
});
}
}